Note that there are some explanatory texts on larger screens.

plurals
  1. POUser is in role "admin" but [Authorize(Roles="admin")] won't authenticate
    text
    copied!<p>I found a great answer on SO describing <a href="https://stackoverflow.com/questions/1822548/mvc-how-to-store-assign-roles-of-authenticated-users/1826413#1826413">how to set up custom user roles</a>, and I've done the same in my project. So in my Login service I have:</p> <pre><code>public ActionResult Login() { // password authentication stuff omitted here var roles = GetRoles(user.Type); // returns a string e.g. "admin,user" var authTicket = new FormsAuthenticationTicket( 1, userName, DateTime.Now, DateTime.Now.AddMinutes(20), // expiry false, roles, "/"); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket)); Response.Cookies.Add(cookie); return new XmlResult(xmlDoc); // don't worry so much about this - returns XML as ActionResult } </code></pre> <p>And in Global.asax.cs, I have (copied verbatim from the other answer):</p> <pre><code>protected void Application_AuthenticateRequest(Object sender, EventArgs e) { var authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { var authTicket = FormsAuthentication.Decrypt(authCookie.Value); var roles = authTicket.UserData.Split(new Char[] { ',' }); var userPrincipal = new GenericPrincipal(new GenericIdentity(authTicket.Name), roles); Context.User = userPrincipal; } } </code></pre> <p>Then, in my <code>ServicesController</code> class, I have:</p> <pre><code>[Authorize(Roles = "admin")] //[Authorize] public ActionResult DoAdminStuff() { ... } </code></pre> <p>I login as a user with the "admin" role, and that works. Then I call /services/doadminstuff - and I get access denied, even though when I put a breakpoint in Global.asax.cs, I can see that my roles do include "admin". If I comment out the first <code>Authorize</code> attribute (with roles) and just use a plain vanilla <code>Authorize</code>, then I can access the service.</p> <p>I must be missing something critical here - but where to start looking?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload