1

I'm writing a Rest API using Asp.Net Core 2 using the comon pattern (Controller, Service, Repository).

Let's say I have an entity E which I GET, POST, PUT and Delete. Now I would like to allow CRUD operation on this entity according to Roles permissions like the table in this post: [1]: JWT Token based Authorization with user permission Asp.net core 2.0

I started defining a Claim for each CRUD operation and the according policy as follow (here E is the entity user as example):

 services.AddAuthorization(options =>
        {
            options.AddPolicy("User.Read", policy =>
            policy.RequireAssertion(context => context.User.HasClaim(c => (c.Type == "Permission") && c.Value == "User.Read")));
            options.AddPolicy("User.Create", policy =>
            policy.RequireAssertion(context => context.User.HasClaim(c => (c.Type == "Permission") && c.Value == "User.Create")));
            options.AddPolicy("User.Update", policy =>
            policy.RequireAssertion(context => context.User.HasClaim(c => (c.Type == "Permission") && c.Value == "User.Update")));
            options.AddPolicy("User.Delete", policy =>
            policy.RequireAssertion(context => context.User.HasClaim(c => (c.Type == "Permission") && c.Value == "User.Delete")));
        });

    [Route("api/[controller]")]
public class UserController : AbstractController<User, IUserService, int>
{

    public UserController(IUserService service) : base(service)
    {
    }
    [Authorize(Policy = "User.Delete")]
    public override Task<IActionResult> Delete(int id)
    {
        return base.Delete(id);
    }
    [ Authorize(Policy = "User.Read")]
    public override Task<IActionResult> Get(int id)
    {
        return base.Get(id);
    }

    [Authorize(Policy = "User.Read")]
    public override Task<IActionResult> GetAll() => base.GetAll();

    [ Authorize(Policy = "User.Create")]
    public override Task<IActionResult> Post([FromBody] User entity)
    {
        return base.Post(entity);
    }
    [ Authorize(Policy = "User.Update")]
    public override Task<IActionResult> Put(int id, [FromBody] User entity)
    {
        return base.Put(id, entity);
    }
}

In this way, at the authentication stage, I check what is the role of the user and get all the permission claims for this role. Then I add the claims in the JwtSecurityToken.

Is this a good practice? I think there a limitation in the number of claims due to the size of the token header then?

What is the best practice to

Fede
  • 804
  • 1
  • 10
  • 21
  • No, this is not best practice. Claims are supposed to model the identity of a user, not permissions. Take a look at my answer here: https://stackoverflow.com/questions/51883273/rights-based-authorization-with-asp-net-core-2-1-identity/51892091#51892091 –  Aug 17 '18 at 14:23
  • Look into attribute based access control (ABAC, XACML, ALFA) which are models meant to address crud authorization – David Brossard Aug 18 '18 at 23:10

0 Answers0