ASP.net Core CRUD授权最佳实践

时间:2018-08-17 08:18:44

标签: authentication asp.net-core authorization claims-based-identity

我正在使用通用模式(控制器,服务,存储库)使用Asp.Net Core 2编写Rest API。

比方说,我有一个实体E,该实体我已被GET,POST,PUT和Delete删除。 现在,我想根据“角色”权限(如本表中的表格)允许对此实体执行CRUD操作:[1]:JWT Token based Authorization with user permission Asp.net core 2.0

我开始为每个CRUD操作和相应的策略定义一个Claim,如下所示(这里E是实体用户):

 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);
    }
}

通过这种方式,在身份验证阶段,我将检查用户的角色,并获取该角色的所有权限声明。然后,将声明添加到JwtSecurityToken中。

这是一个好习惯吗?我认为,由于令牌标头的大小,索偿的数量受到限制吗?

什么是最佳实践

0 个答案:

没有答案