gpt4 book ai didi

c# - 不同角色的不同 API 功能

转载 作者:行者123 更新时间:2023-11-30 12:38:23 24 4
gpt4 key购买 nike

我有 asp.net core 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();
}

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

最佳答案

为了检查用户是 Admin 还是 Author 的权限,您可以实现 multiple requirements 作为来自@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 中注册Requirement

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

关于c# - 不同角色的不同 API 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53186143/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com