Set role access control for Asp.net MVC Forms authentication

Source: Internet
Author: User

When we use Asp.net MVC forms to authenticate users and set the authorize attribute of controller or action, only the users attribute can be set by default (here users usually refers to the user login name ), we cannot directly set user role information. When creating an application that depends on the role (and do not want to bother configuring membership), we need to add role information to the authenticated user. The following describes how to apply role information:

1. Web. config configuration. The following settings indicate that we use forms authentication. All unauthorized users cannot access the controllers and actions with the authorize flag.

<system.web>

<authentication mode="Forms"><forms loginUrl="~/Account/LogOn" timeout="2880" cookieless="UseCookies" path="/" name=".ASPXAUTH" /></authentication><authorization><deny users="?"/></authorization></system.web>

2 Global. asax. CS adds the verification request Event code. If the user information has been set, the user object with the role information is re-constructed. The role information is obtained from the userdata attribute of the Identity credential ticket, multiple roles are separated by commas.

 protected void Application_AuthenticateRequest(object sender, EventArgs e)        {            var app = sender as HttpApplication;            if (app.Context.User!=null)            {                var user = app.Context.User;                var identity = user.Identity as FormsIdentity;                // We could explicitly construct an Principal object with roles info using System.Security.Principal.GenericPrincipal                var principalWithRoles = new GenericPrincipal(identity, identity.Ticket.UserData.Split(','));                // Replace the user object                app.Context.User = principalWithRoles;                           }        }

By default, the role information is empty, for example:

After replacement, such:

 

3. After the user legality is verified, construct encrypted identity creden。 with role information, and store the role information in the userdata of the ticket.

        [HttpPost]        public ActionResult LogOn(User user)        {            // check user by quering database or other ways. skip this logic.            string userRoles = "admin,user,powerUser";            bool isPersistent = true;            int version = 0;            double persistentMinutes = 60.00; // minutes            string userName = user.Name;            string cookiePath = FormsAuthentication.FormsCookiePath;            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(version, userName, DateTime.Now, DateTime.Now.AddMinutes(persistentMinutes), isPersistent, userRoles, cookiePath);            string encryptedTicket = FormsAuthentication.Encrypt(ticket);            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);            Response.Cookies.Add(cookie);            return Redirect(Request.QueryString["returnUrl"]);        }

4. Use Role information to control the user's access to controller or action. Because we set the user to have the admin, user, and poweruser roles, the user has the right to access this method.

Public class homecontroller: controller {[authorize (roles = "Admin, poweruser")] public actionresult index () {// The user has the admin, user, and poweruser roles, therefore, you can access this method. Return view ();}}

5. The following is the source code of the authorizeattribute authorizecore method. We can see that as long as the user has any role in the authorizeattribute. Roles setting, the authorizeattribute can be reviewed.

  // This method must be thread-safe since it is called by the thread-safe OnCacheAuthorization() method.        protected virtual bool AuthorizeCore(HttpContextBase httpContext)        {            if (httpContext == null)            {                throw new ArgumentNullException("httpContext");            }            IPrincipal user = httpContext.User;            if (!user.Identity.IsAuthenticated)            {                return false;            }            if (_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase))            {                return false;            }            if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole))            {                return false;            }            return true;        }

The above applies to Asp.net webforms applications.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.