我有带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();
}
还是应该只检查方法内部的角色?
答案 0 :(得分:1)
要检查用户是Admin
还是Author
的权限,您可以将multiple requirements
作为@ user2884707bond中的文档来实现。
用于您的方案的multiple requrements
。
您可以按照以下步骤操作:
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
}
在Requirement
中注册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();
}