这应该很简单,但我在谷歌搜索之后根本无法弄清楚。这就是我想要的。我有一个要授权的自定义用户表(目前没有角色)。为此,我必须实现一个我已经完成的自定义成员资格提供程序。我的问题是,如何将自定义 IPrincipal 设置为 HttpContext.Current.User?那应该发生在哪里?假设我有以下设置:
public class CustomMembershipProvider : MembershipProvider
{
private IUserRepository _repository;
public CustomMembershipProvider(IUserRepository repository)
{
_repository = repository;
}
public override bool ValidateUser(string username, string password)
{
//check user repository
}
//additional methods omitted for brevity
}
然后我有一个自定义用户类的工具IPrincipal
和IIdentity
public class CustomUser : IPrincipal
{
public CustomUser(string name, int userId, string additionalInfo)
{
Identity = new CustomIdentity(name, userId, additionalInfo);
}
public IIdentity Identity { get; private set; }
public bool IsInRole(string role)
{
return true;
}
}
public class CustomIdentity : IIdentity
{
public CustomIdentity(string name, int userId, string additionalInfo)
{
Name = name;
UserId = userId;
AdditionalInfo = additionalInfo;
}
public string Name { get; private set; }
public string AuthenticationType
{
get { return "CustomAuth"; }
}
public bool IsAuthenticated
{
get { return !String.IsNullOrEmpty(Name); }
}
public int UserId { get; private set; }
public string AdditionalInfo { get; private set; }
}
所以我的问题是,将 Context.User 设置为此自定义用户的实例的正确位置在哪里?我需要自定义授权属性吗?如果是这样,那会是什么样子?