Spook
Spook

Reputation: 25919

Authorize(Roles="Admin") does not work

I'm writing ASP.NET application with Identity as authorization engine. I wrote my custom user and role stores and they seem to work correctly. However, for some unknown reason, attempt to use Authorize with role on controller's action fails and redirects to Home/Index. The action looks like following:

[Authorize(Roles = "Admin")]
public ActionResult Manage()
{
    return View();
}

The redirection is being done silently, so I cannot hook debugger anywhere (especially that action filtering is being done before running action).

I guess this may not be enough to diagnose the problem, so just tell me in comments, what additional information do you need and I'll edit the question.

Why doesn't it work?


Edit: Configuration in Startup.cs

    public void Configuration(IAppBuilder app)
    {
        DataProtectionProvider = app.GetDataProtectionProvider();

        app.CreatePerOwinContext<ApplicationUserManager>(() => DependencyResolver.Current.GetService<ApplicationUserManager>());

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = "ApplicationCookie",
            LoginPath = new PathString("/Account/Login")
        });            
    }

Edit: Another action:

    [AllowAnonymous]
    public async Task<ActionResult> Index()
    {
        // This returns FALSE
        if (User.IsInRole("Admin"))
            System.Diagnostics.Debug.WriteLine("Ok");

        var userManager = UnityConfig.Container.Resolve<ApplicationUserManager>();
        // This returns TRUE
        if (await userManager.IsInRoleAsync(User.Identity.GetUserId<int>(), "Admin"))
            System.Diagnostics.Debug.WriteLine("Ok");

        return View();
    }

Upvotes: 1

Views: 9078

Answers (1)

Joachim L&#248;vf
Joachim L&#248;vf

Reputation: 118

A couple of things to check:

  1. What is the login page set to? I'm guessing you are either unauthenticated or unauthorized, and MVC is sending you to the login page (which is probably set or defaulted to "/"
  2. If you are sure you are logged in (authenticated), double check that your user does indeed have the admin role (is authorized).
  3. I believe the user store has a method you can override to see what's returned for the user's roles. It's probably worth setting a breakpoint there and see what's going on.

Upvotes: 3

Related Questions