Role based Authorization in ASP.net MVC 4

前端 未结 1 697
孤独总比滥情好
孤独总比滥情好 2021-01-28 08:30

I\'m working on creating a role system in ASP.net. Now it works fine because I can associate roles to users

As you can see here.

Now my question is what

相关标签:
1条回答
  • 2021-01-28 09:32

    You need to add roles in UserPrincipal in Global.asax file

    protected void Application_AuthenticateRequest(Object sender, EventArgs e) 
    {  
        HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
    
        if (authCookie != null) 
        {
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            // Read the roles from cookie
            string[] roles = authTicket.UserData.Split(new Char[] { ',' });
    
            GenericPrincipal userPrincipal = new GenericPrincipal(new GenericIdentity(authTicket.Name), roles);
            Context.User = userPrincipal;
        }
    }
    

    Create a customized Authorize attribute and override OnAuthorization method

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        // Check if the user is authorized to access else redirect to unauthorized page
        base.OnAuthorization(filterContext);
    }
    
    0 讨论(0)
提交回复
热议问题