这应该很简单,但我在谷歌搜索后根本无法弄清楚。这就是我想要的。我有一个我想授权的自定义用户表(目前没有角色)。为此,我必须实现一个自定义的 Membership Provider,我已经完成了。不过,我的问题是,如何将自定义 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 设置为此自定义用户的实例的正确位置在哪里?我需要自定义授权属性吗?如果是这样,那会是什么样子?
最佳答案
我建议为所有 Controller 使用自定义 Controller 基类
然后,在OnAuthorization
中调用
protected override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
{
// Actual Authentication
HttpContext.User = user;
Thread.CurrentPrincipal = user;
base.OnAuthorization(filterContext);
}
我不完全确定如何调用成员资格提供程序,因为我是手动执行的,但我认为您可以静态访问 Membership.Provider
以执行实际的对象构造。
Do I need a custom Authorize Attribute?
没有。注意身份验证和授权的区别:身份验证在您的系统中建立用户身份。授权允许或拒绝特定请求。因此,AuthorizeAttribute
也有一个 Roles
参数,以允许仅由特定用户调用操作。
关于c# - 在 ASP.NET MVC 中使用表单例份验证的自定义 IPrincipal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7140109/