[Authorize(Roles = "Admin")]
is not working for me.
In startup.cs
(ConfigureServices
) I have:
services.AddDbContextPool<AppDbContext>(
options => options.UseSqlServer(Configuration.GetConnectionString("defaultCon")));
services.AddAuthentication().AddCookie();
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddRoles<IdentityRole>()
.AddRoleManager<RoleManager<IdentityRole>>()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<AppDbContext>()
.AddErrorDescriber<CustomIdentityErrorDescriber>()
.AddClaimsPrincipalFactory<MyUserClaimsPrincipalFactory>();
And in the Configure
method I have:
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Employee}/{action=list}/{id?}")
.RequireAuthorization();
});
I don't know what is my mistake.
If you are using JWT based authorization then we need to add the roles on the Claim Class as below:
After adding the roles to the Claim Class the authorize tag should work automatically.