1 回答
TA贡献1810条经验 获得超5个赞
asp.net core中相关的API有:
授权服务
授权策略
授权要求
IAuthorizationHandler
您正在寻找的授权模式称为 Resource-based authorization
https://learn.microsoft.com/en-us/aspnet/core/security/authorization/resourcebased?view=aspnetcore-2.2
基本上,您可以定义 AuthorizationPolicy,并将其应用于资源实例:
var ticket = _ticketRepository.Find(ticketID);
var authorizationResult = await _authorizationService
.AuthorizeAsync(User, ticket, "EditTicketPolicy");
在授权处理程序中,您可以检查用户是否是资源的所有者。
public class ResourceOwnerRequirement : IAuthorizationRequirement
{
}
public class ResourceOwnerHandler
: AuthorizationHandler<ResourceOwnerRequirement, MyBusinessObject>
//: AuthorizationHandler<ResourceOwnerRequirement> use this overload to handle all types of resources...
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
ResourceOwnerRequirement requirement,
MyBusinessObject resource)
{
int createdByUserId = resource.CreatedBy;
Claim userIdClaim = ((ClaimsIdentity)context.User.Identity).FindFirst("UserId");
if (int.TryParse(userIdClaim.Value, out int userId)
&& createdByUserId == userId)
{
context.Succeed(requirement);
}
}
}
//admin can do anything
public class AdminRequirementHandler : IAuthorizationHandler
{
public Task HandleAsync(AuthorizationHandlerContext context)
{
if (context.User.Claims.Any(c => c.Type == "Role" && c.Value == "Administator"))
{
while (context.PendingRequirements.Any())
{
context.Succeed(context.PendingRequirements.First());
}
}
return Task.CompletedTask;
}
}
顺便说一句,这仍然可以称为声明或基于角色的授权。具有特定角色的用户可以编辑自己的工单,但具有管理员角色的用户还可以编辑其他工单。不同之处在于您将授权应用于资源,而不仅仅是操作
- 1 回答
- 0 关注
- 117 浏览
添加回答
举报