ASP.NET MVC implements the handling method of role based permission control

  • 2020-05-30 19:52:12
  • OfStack

[Authorize]
public ActionResult Index()

The way of marking can realize that the marked ACTION must be authenticated user to access;

Through the use of

[Authorize(Users="username")]

The marked ACTION can be accessed only by a specific user. The above two methods are very convenient to use. There is already a complete implementation process in the sample program of NeedDinner.

However, most of the authentication methods we use in the practical application are role-based (Roles) authentication method, which is not given in NeedDinner. This paper gives the concrete implementation (ASP.NET Forms authentication) process:

step 1
After completing the UserName and Password authentication, write the authentication Cookie to the client

code


        FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
            1,
            userName,
            DateTime.Now,
            DateTime.Now.AddMinutes(20),
            false,
            "admin"// Write user roles 
            );

        string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

        System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
        System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);

step 2
Add the following code to the Global.asax.cs file to read Cookie when the user logs on to the site

code


protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
        if (authCookie == null || authCookie.Value == "")
        {
            return;
        }
        FormsAuthenticationTicket authTicket = null;
        try
        {
            authTicket = FormsAuthentication.Decrypt(authCookie.Value);
        }
        catch
        {
            return;
        }
        string[] roles = authTicket.UserData.Split(new char[] { ';' });
         if (Context.User != null)
        {
            Context.User = new System.Security.Principal.GenericPrincipal(Context.User.Identity, roles);
        }
    }

step 3

This way, you can use the following effect


  [Authorize(Roles="admin")]
    public ActionResult Index(int ? page)


Related articles: