c# – 针对不同角色的不同API功能

我有asp.net核心2.1的API.基于声明的身份验证.是否可以将这两个api功能合二为一?

[Authorize(Roles = "Admin")]
[HttpPost("delete")]
public IActionResult Delete([FromBody]Item item)
{
    _itemService.Delete(item.Id);
    return Ok();
}

[Authorize]
[HttpPost("delete")]
public IActionResult Delete([FromBody]Item item)
{
    var id = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
    if (_itemService.IsAuthor(id))
    {
        _itemService.Delete(item.Id);
        return Ok();
    }
    return Forbid();
}

或者我应该检查内部方法的角色?

最佳答案 要检查用户是管理员还是作者的权限,您可以实现多个要求作为来自@ user2884707bond的文档.

用于为您的方案使用多个要求.

您可以按照以下步骤操作:

> PermissionHandler.cs

        public class PermissionHandler : IAuthorizationHandler
{
    public Task HandleAsync(AuthorizationHandlerContext context)
    {
        var pendingRequirements = context.PendingRequirements.ToList();

        foreach (var requirement in pendingRequirements)
        {
            if (requirement is ReadPermission)
            {
                if (IsOwner(context.User, context.Resource) ||
                    IsAdmin(context.User, context.Resource))
                {
                    context.Succeed(requirement);
                }
            }
            else if (requirement is EditPermission ||
                     requirement is DeletePermission)
            {
                if (IsOwner(context.User, context.Resource))
                {
                    context.Succeed(requirement);
                }
            }
        }
        return Task.CompletedTask;
    }
    private bool IsAdmin(ClaimsPrincipal user, object resource)
    {
        if (user.IsInRole("Admin"))
        {
            return true;
        }
        return false;
    }

    private bool IsOwner(ClaimsPrincipal user, object resource)
    {
        // Code omitted for brevity

        return true;
    }

    private bool IsSponsor(ClaimsPrincipal user, object resource)
    {
        // Code omitted for brevity

        return true;
    }
}

>要求

    public class ReadPermission : IAuthorizationRequirement
{
    // Code omitted for brevity
}
public class EditPermission : IAuthorizationRequirement
{
    // Code omitted for brevity
}
public class DeletePermission : IAuthorizationRequirement
{
    // Code omitted for brevity
}

> Startup.cs中的注册要求

        services.AddAuthorization(options =>
    {
        options.AddPolicy("Read", policy => policy.AddRequirements(new ReadPermission()));                
    });
    services.AddSingleton<IAuthorizationHandler, PermissionHandler>();

>使用

 [Authorize(Policy = "Read")]
 [HttpPost("delete")]
 public IActionResult Delete([FromBody]Item item)
 {
      _itemService.Delete(item.Id);
      return Ok();
  }
点赞