Reputation: 470
Authorize Attribute not working in ASP Core 2.2 when placed on top of a controller. I have my startup.cs configured like this.
//Add Claims
services.AddScoped<IUserClaimsPrincipalFactory<User>, UserClaimsPrincipalFactory<User, Role>();
//Add Context
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddHttpContextAccessor();
services.AddDbContext<DbContext>();
services.AddIdentity<User, Role>(
config =>
{
config.SignIn.RequireConfirmedEmail = true;
config.User.RequireUniqueEmail = true;
}
)
.AddRoles<Role>()
.AddRoleManager<RoleManager<Role>>()
.AddDefaultUI(UIFramework.Bootstrap3)
.AddDefaultTokenProviders()
.AddClaimsPrincipalFactory<MyUserClaimsPrincipalFactory>()
.AddEntityFrameworkStores<DbContext>();
//Add MVC
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddAuthorization();
services.AddAuthentication();
The UserClaimsPrincipalFactory works as it should and I'm able to access the claims in the view via UserManager and filter links based on the role in the claims.
But when I do this on the controller.
[Authorize(Roles = "Administrator")]
[HttpGet]
public async Task<IActionResult> Index()
{
return View();
}
It doesn't work and I get access denied despite having the required roles in identity. Is this a known bug and has anyone managed to get role attributes working in ASP Core 2.2?
Upvotes: 0
Views: 627
Reputation: 470
I have gotten Roles based on claims working in ASP Core 2.2. Roles without claims aren't working (this could be fixed in ASP Core 3.0).
You need to add values to the RoleClaim & UserClaim tables after creating Roles (Role table) and Adding users to those roles (UserRole table).
Edit...
Basically add users to roles & use the claimtypes.role in your IUserClaimsPrincipalFactory to return a role or add userclaim roles manually using usermanager & rolemanager.
Upvotes: 0
Reputation:
//Add Claims
services.AddScoped<IUserClaimsPrincipalFactory<User>,
UserClaimsPrincipalFactory<User, Role>();
//these should be move AddMvc
services.AddAuthorization();
services.AddAuthentication();
//Add Context
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddHttpContextAccessor();
services.AddDbContext<DbContext>();
services.AddIdentity<User, Role>(
config =>
{
config.SignIn.RequireConfirmedEmail = true;
config.User.RequireUniqueEmail = true;
}
)
.AddRoles<Role>()
.AddRoleManager<RoleManager<Role>>()
.AddDefaultUI(UIFramework.Bootstrap3)
.AddDefaultTokenProviders()
.AddClaimsPrincipalFactory<MyUserClaimsPrincipalFactory>()
.AddEntityFrameworkStores<DbContext>();
//Add MVC
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
Upvotes: 0