MVC 5 custom AuthorizeAttribute

本文关键字:AuthorizeAttribute custom MVC | 更新日期: 2023-09-27 18:15:34

我想实现自定义AuthorizeAttribute

我有自定义用户:

    public class MyUser : IPrincipal
    {
        public List<string> Roles { get; set; }
        public IIdentity Identity{ get; set; } 
        public bool IsInRole(string role){ return Roles.Contains(role); }
    }

In global.asax

    protected void Session_Start(object sender, EventArgs e)
    {
         MyUser user = new MyUser();
         user.Identity = User.Identity;
         user.Roles = new List<string>();
         user.Roles.Add("MyRole");//I will get them from AD
         HttpContext.Current.User = user;
    }

和属性

    public class AuthorizeADAttribute : AuthorizeAttribute
    {
        public string Roles { get; set; }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            MyUser user = (MyUser)httpContext.User;//User is not MyUser
            if (user.Roles.Contains(Roles))
            {
                return true;
            }
            return false;
        }
        protected override void HandleUnauthorizedRequest(
        AuthorizationContext filterContext)
        {
            ...
        }
    }

问题是httpContext.User返回System.Security.Claims.ClaimsPrincipal。为什么会发生这种情况?我如何从session_start访问我的用户?

MVC 5 custom AuthorizeAttribute

您需要在Global.asax.cs中覆盖Application_PostAuthenticateRequest事件处理程序中的值。

请看下面的答案:https://stackoverflow.com/a/10524305/54937

相关文章:
  • 没有找到相关文章