2

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
masoud
  • 31
  • 4
  • Could you please tell me how you add the role for the user? What you mean about [Authorize(Roles = "Admin")] is not working for me? – Brando Zhang Jun 22 '21 at 09:26

2 Answers2

0

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.

Abinesh Amatya
  • 160
  • 1
  • 1
  • 7
  • Where should I add this code? now when I login with admin role user, "access denied" page appears... – masoud Jun 21 '21 at 17:43
  • Firstly, could you tell me are you using JWT based authentication or not? If yes, then it should be added while generating the JWT token. Moreover, could you check this on while login whether the role is assigned to the person and returned from the database: var userToVerify = await _userManager.FindByNameAsync(model.UserName); var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, false); var roles = await _userManager.GetRolesAsync(userToVerify); //check whethere the role is assigned and returned from the database – Abinesh Amatya Jun 22 '21 at 04:39
0

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

Pritom Sarkar
  • 2,154
  • 3
  • 11
  • 26
  • SSL is active in my server, but Role-based authorization still not working – masoud Jun 21 '21 at 17:57
  • @masoud remove ```services.AddAuthentication().AddCookie();```also add just ```services.AddIdentity() .AddEntityFrameworkStores() .AddDefaultTokenProviders();``` remove this related code in your startup.cs and add this code and try again. – Pritom Sarkar Jun 21 '21 at 18:20