Role-based authorization not working in ASP.NET Core 3.1

297 Views Asked by At

[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.

2

There are 2 best solutions below

2
On

If you are using JWT based authorization then we need to add the roles on the Claim Class as below:

         var claims = new List<Claim> {
                new Claim("role", "Admin") // your person logged in role                                
         };

After adding the roles to the Claim Class the authorize tag should work automatically.

2
On

Looking like everything ok with your code. by the way, Just Enable SSL, and I think then it should work fine.