Masha
Masha

Reputation: 1

Role-based claims auth doesnt work ASP.NET Core Identity

I have problem: I'm using ASP.NET Core Identity.

Relation between users, claims and roles are as follows: users have roles, roles have claims.

My claims are saved in the AspNetRoleClaims table, roles in the AspNetRoles table, and users in AspNetUsers.

Users are connected to roles through AspNetUserRoles.

Now my user has CreateRole permission, but CreateRole endpoint returns a http 403 forbidden error.

What am I doing wrong?

Please help me :)

This is my program.cs:

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("RoleModulePolicy", policy => policy.RequireClaim("RoleModule"));
    options.AddPolicy("CreateRolePolicy", policy => policy.RequireClaim("CreateRole"));
    options.AddPolicy("EditRolePolicy", policy => policy.RequireClaim("EditRole"));
    options.AddPolicy("DeleteRolePolicy", policy => policy.RequireClaim("DeleteRole"));
});

ClaimsStore.cs file

public static class ClaimsStore
{
    public static List<Claim> GetAllClaims()
    {
        return new List<Claim>()
        {
            new Claim("RoleModule", "Role Module"),
            new Claim("CreateRole", "Create Role"),
            new Claim("EditRole", "Edit Role"),
            new Claim("DeleteRole", "Delete Role"),
        };
    }
}

Controller:

[Authorize(Policy = "CreateRolePolicy")]
[HttpPost("[action]")]
public async Task<IActionResult> CreateRole(RoleCreateRequestModel model)
{
    var result = await _roleManagementService.CreateRole(model);

    if (result.Succeeded)
    {
        return Ok(result);
    }
    else
    {
        return BadRequest(result);
    }
}

Upvotes: 0

Views: 79

Answers (1)

Fengzhi Zhou
Fengzhi Zhou

Reputation: 1637

Considered the lack of some details, please check the steps to see if there are any mistakes.

1.Register the role service in Program.cs

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>(); 

2.Directly register the claims in program.cs

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("CreateRolePolicy", policy => 
    policy.RequireClaim("CreateRole","Create Role"));
    ...
});

Based on your description , your are using a user account , whose role has claims of creating roles to meet the policy. Just in case, whether AspNetUserClaims or AspNetRoleClaims will be checked , but to match logic of your design , better follow these steps.

3.Create a role.

4.Assign RoleClaim to the role.

5.Assign the role to the user

Tested in my local brand new AspNetCore Identity project , worked as expected, anything confused please feel free to share.

Upvotes: 0

Related Questions