For future people with a similar problem - it could depend on how you are actually setting up your roles on the current user.
I had a similar issue where the roles were being pulled out of the cookie in an override of OnActionExecuting
in a base controller. Turns out this was executing after the [Authorize]
attribute, so the roles weren't actually set up when the attribute was checking for them. The call to User.IsInRole
, being in the View, was executing after OnActionExecuting
, so it saw the roles fine.
So User.IsInRole
returned what I expected, but the [Authorize]
attribute did not.
I was able to resolve this by moving the code for getting the roles into a more sensible place, that executes before the Authorize attribute - for example, in Global.asax.cs:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
// do stuff in here
}
Or even better, in your own custom attribute - see https://stackoverflow.com/a/5314736/206297.