views:

50

answers:

2

In my AccountController, I have code like this:

ControllerContext.HttpContext.User = new MyAppUserPrincipal(user);

When I step through this in the debugger I can see that ControllerContext.HttpContext.User.IsInRole("Admin") is true.

Next, I have a HomeController protected by a custom attribute:

[AuthorizeMyApp(Roles = "Admin")]

In the definition of the attribute, I have this:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    var principal = filterContext.HttpContext.User ;
    if (! principal.IsInRole(_roles) )

etc.

Here's what's weird, after logging in and trying to go to Home:

principal.Identity.Name has the expected name, and IsAuthenticate is true; however a) principal.IsInRole("Admin") is false b) (principal As MyAppUserPrincipal) is null

Am I doing something wrong here? (using MVC2)

A: 

I'm also new to MVC2 but thought I'd chip in. Could it be because you're not doing the actual authorization in the AuthorizeCore(HttpContextBase httpContext) method?

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        return httpContext.User.IsInRole("Admin");
    }
}
TheCloudlessSky
A: 

Hi - thanks for the answer, but the truth turned out to be that there were two separate requests going on: the Logon to set the cookies, but the redirect after the Logon (which caused the Authorize attribute to fire) was a separate request. As in any ASP.NET app, the place to put your custom user into context is still Application_BeginRequest in global.asax. I think my lack of confidence in my MVC skill level was blinding me to what I already knew how to do. Sorry to inconvenience anyone - hope this answer helps.