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.