[MVC5] Permission + role, mvc5 permission role
1. Set the User Role in Ticket
In the Ticket permission, set the user role (separated by commas ).
List <string> roles = new List <string> (); if (isAdmin) {roles. add ("Admin");} roles. add ("Guest"); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1, model. userId, DateTime. now, DateTime. now. addDays (30), // set the logon time to remember (30 days here) true, String. join (",", roles); // sets the User Role HttpCookie cookie = new HttpCookie (FormsAuthentication. formsCookieName, FormsAuthentication. encrypt (ticket); // set the cookie expiration time (50 years. expires = DateTime. now. addYears (50); Response. cookies. add (cookie );
2. Add the Application_AuthenticateRequest method to Global. asax. cs.
Protected void Application_AuthenticateRequest (object sender, EventArgs e) {// obtain the Cookie HttpCookie = Context. request. cookies [FormsAuthentication. formsCookieName]; if (cookie = null) return; // decrypt FormsAuthenticationTicket ticket = null; try {ticket = FormsAuthentication. decrypt (cookie. value);} catch (Exception) {return;} if (ticket = null) return; // get ticket. role st set in UserData Ring [] roles = ticket. UserData. Split (new char [] {','}); // In From authentication, use the GenericPrincipal class in the IPrincipal object. // This class consists of the FormsIdentity class indicating the qualification intelligence and the role information (string [] object. FormsIdentity identity = new FormsIdentity (ticket); GenericPrincipal principal = new GenericPrincipal (identity, roles); // assign FormsIdentity to Context. user // you can view. user to obtain the value Context. user = principal ;}
3. Use the Authorize feature in the Controller
// Allow anonymous access to [AllowAnonymous] public class HomeController: Controller {......} // only Allow logon users to access [Authorize] public class SampleController: Controller {......} // only users with the "Admin" role can access [Authorize (Roles = "Admin")] public class SampleController: Controller {......} // This feature can also be used for Action
Reference: http://www.atmarkit.co.jp/ait/articles/0307/26/news002_2.html
Synchronized to [MVC5] ASP. net mvc project note summary