Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core 3.1 role based authorization fails, getting 403 exception

I am trying to use Microsoft Identity library to do a role base authorization and I am failing.

  • I can authenticate the user
  • I see the role that user is belonging to matches the Role I have on the controller
  • When I go to that controller I get 403 Forbidden error

I don't know how to debug it further.

Startup:

services.AddIdentity<User, UserRole>(opt => opt.User.RequireUniqueEmail = true)
    .AddRoles<UserRole>()
    .AddEntityFrameworkStores<EntityDbContext>()
    .AddDefaultTokenProviders();

var jwtSetting = _configuration
    .GetSection("JwtSettings")
    .Get<JwtSettings>();

services.AddAuthentication(options => {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(config =>
    {
        config.RequireHttpsMetadata = false;
        config.SaveToken = true;

        config.TokenValidationParameters = new TokenValidationParameters
        {
            ValidIssuer = jwtSetting.Issuer,
            ValidAudience = jwtSetting.Audience,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSetting.Key))
        };
    });

My Controller with a role:

[Authorize(Roles = "Internal")]
[ApiController]
[Route("Api/[controller]")]
public class UserController : BasicCrudController<User>
{
     // Stuff here ...
}

Repo url

like image 457
Node.JS Avatar asked Feb 05 '20 16:02

Node.JS


1 Answers

You should add a claim of type ClaimsIdentity.RoleClaimType into jwt token for its role

like image 135
Saeed Gholamzadeh Avatar answered Nov 11 '22 04:11

Saeed Gholamzadeh