Authorize Roles error in ASP.NET Core 2.0: Just log out, then log in

You know you can use Identity to add authorization logic to your .NET project. In the case of ASP.NET Core MVC, we can add an Authorize attribute to a Controller or to an Action, and then, only authenticated people will be able to access that Controller/Action. Furthermore, you can specify if the user also has to be a member of a specific role.

In general this work as expected, but there is a small caveat: If you are adding a user to a role, and said user is logged in, he may not be able to access an Action/Controller that’s behind an Authorize(Role = “MyRole”) attribute until he logs in again. Here’s why.

The issue arises because Identity (the part of .NET that works with Authentication and Authorization) works with Claims. These gets assigned when the user is logged in the application. If the user is added to a role, but he is currently logged in, then he may not get the Claim that indicates that he’s on the role, but he’ll have to Log out, then Log in to the app to get that claim. Let’s see an example:

The following code creates the Admin role, and then adds the current user to said role:


if (User.Identity.IsAuthenticated)
{
   await roleManager.CreateAsync(new IdentityRole("Admin"));
   var user = await userManager.GetUserAsync(HttpContext.User);
   await userManager.AddToRoleAsync(user, "Admin");
}

Now, let’s say we have the following code that indicates that only users in the Admin role can access the Contact action:


[Authorize(Roles = "Admin")]
public IActionResult Contact()
{
   ViewData["Message"] = "Your contact page.";

   return View();
}

Now, if you register a new user in your app, and run the code to add him to the Admin role, if you try to go to the Contact Action, you’ll get an access denied page.  To solve this issue, just log out, and then log in again, and the issue will be solved.

When you get weird errors like this, always check that user claims, to see if there is something missing:


if (User.Identity.IsAuthenticated)
{
   // get user's claims
   var claims = User.Claims.ToList();

}

Summary

If you are getting weird authentication errors, sometimes it is advisable to try to log out and then log in, so you can get the latest user’s claims.

In case you want it, here’s the code in this post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s