Authorized attribute does not work with roles

I'm having trouble getting the Authorize attribute to work with roles. Here's how I decorated my controller:

 [Authorize(Roles = "admin")] public ActionResult Index() { ... } 

and I register the user:

 string roles = "admin"; FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket( 1, username, DateTime.Now, DateTime.Now.AddMinutes(30), false, roles ); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket)); HttpContext.Current.Response.Cookies.Add(cookie); 

But my user is still denied access. Where am I mistaken?

+4
source share
1 answer

I came across a similar example of your code: MVC 's highest voice response - How to store / assign authenticated user roles .

The authorized attribute calls the IsInRole method on the IPrincipal stored in HttpContext.User . By default, IPrincipal has no roles, in which case IsInRole will always return false. This is why access to your action is denied.

Since you saved the user roles in the FormsAuthenticationTicket UserData property , you must extract the roles from the auth cookie and into the IPrincipal instance itself. MVC's Highest Voice Response - How to store / assign authenticated user roles provides code that you can add directly to your global.asax.cs file to do this, I repeated this below:

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

Source: https://habr.com/ru/post/1502220/


All Articles