'Authorize attribute does not work with roles
I have a controller level authorize attribute set up like this
[Authorize(Roles = "Administrator")]
And I am adding claims to my user with an overriden UserClaimsPrincipalFactory class that is generates claims like this:
protected override async Task<ClaimsIdentity> GenerateClaimsAsync(ApplicationUser user)
{
var role = await UserManager.GetRolesAsync(user);
var identity = await base.GenerateClaimsAsync(user);
identity.AddClaim(new Claim(Options.ClaimsIdentity.RoleClaimType, role.FirstOrDefault()));
return identity;
}
But the due to the authorize attribute, my request that use it, are returning 403, even when the user has the Administrator role.
I have seen numerous problems like this on stackoverflow and on the web, but none of the solutions worked for me.
I have checked multiple times, that I use the correct user, with the correct roles assigned.
EDIT: Added relevant parts from the ConfigureServices method:
services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddClaimsPrincipalFactory<MyUserClaimsPrincipalFactory>();
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
services.AddAuthentication()
.AddIdentityServerJwt();
And relevant code from Configure method from Startup.cs:
app.UseAuthentication();
app.UseIdentityServer();
app.UseAuthorization();
I also tried to use policy based authorization with this code and related decorators, but that did not help either:
services.AddAuthorization(options =>
{
options.AddPolicy("AdministratorOnly", policy => policy.RequireClaim(ClaimTypes.Role,"Administrator"));
});
Solution 1:[1]
Try to set a break point to check the "role.FirstOrDefault()" value, whether it is "Administrator" or not (note the spelling).
Besides, try to use identity.AddClaim(new Claim(ClaimTypes.Role, "Administrator"));,
you can refer this screenshot and set the break point in your sample to check the claims:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zhi Lv |

