c# - 在 ASP.NET MVC 中使用表单例份验证的自定义 IPrincipal

标签 c# asp.net-mvc authorization iprincipal

这应该很简单,但我在谷歌搜索后根本无法弄清楚。这就是我想要的。我有一个我想授权的自定义用户表(目前没有角色)。为此,我必须实现一个自定义的 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 
}

然后我有一个自定义用户类,它实现了 IPrincipalIIdentity

 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/

相关文章:

javascript - 服务器和浏览器日期差异

jquery - 验证预填充的 jQuery 表单(第一个字段清除时无效,ASP.NET 且不显眼)

javascript - 在跨站点域中自动登录

c# - 如何在 LINQ to Entities 中重用字段过滤器

c# - 检查两个泛型类型是否相等

jquery - 如何从 ASP.NET MVC cshtml 获取授权信息并将其设置为 jquery ajax 的 Headers ["Authorization"]

yii - Yii 框架中角色代码应该放在哪里?

asp.net-mvc-4 - MVC4 - 具有标准授权属性的基于声明的授权

函数调用中的 C# 委托(delegate)

c# - 如何流式传输字节数组图像?