gpt4 book ai didi

asp.net-core - 如何在 ASP.Net Core 中组合/组合授权处理程序?

转载 作者:行者123 更新时间:2023-12-01 19:47:50 24 4
gpt4 key购买 nike

如何重复使用 AuthorizationHandlers 组成一个复合 Material requirement两个处理程序的?

  • RequirementA使用一个处理程序 IsAllowedAccessToA : AuthorizationHandler<RequirementA>
  • RequirementB使用一个处理程序 IsAllowedAccessToB : AuthorizationHandler<RequirementB>
  • RequirementA_OR_B如果满足IsAllowedAccessToA在哪里或IsAllowedAccessToB成功了

我的资源只能由 RequirementA 访问RequirementB 也一样。我还有 A 或 B 可以使用的资源。

我不知道如何在不重复的情况下做到这一点 IsAllowedAccessToAIsAllowedAccessToB处理程序

This article有帮助,但用例并不完全相同。

最佳答案

试试这个:

你的要求类是这样的:

public class PermissionRequirement : IAuthorizationRequirement
{
public PermissionRequirement(string permission)
{
this.Permission = permission;
}

public string Permission { get; }
}

处理程序应该是这样的:

public class PermissionAuthorizationHandler : AuthorizationHandler<PermissionRequirement>
{
private readonly IPermissionProvider _permissionProvider;

private readonly IUserProvider _userProvider;

public PermissionAuthorizationHandler(IPermissionProvider permissionProvider, IUserProvider userProvider)
{
// permissionProvider is a class that has a function called hasClaim, with bool return value that takes user id and claim as input arguments and realize weather the user id has access to the controller or not
this._permissionProvider = permissionProvider;

// userProvider, return the id of current user
this._userProvider = userProvider;
}

protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
{
var hasClaim= await this._permissionProvider.HasClaim(this._userProvider.GetUserId(), requirement.Permission)
.ConfigureAwait(false);

if (hasClaim) context.Succeed(requirement);
else
context.Fail();
}
}

关于asp.net-core - 如何在 ASP.Net Core 中组合/组合授权处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45525008/

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