在授权策略中获取 ActionContext

时间:2021-06-07 11:54:01

标签: c# asp.net-core asp.net-authorization

我想定义一个策略,默认情况下拒绝所有在 JWT 不记名令牌中具有 UnTrusted 声明的请求。但是,应该有一个选项可以通过向控制器的操作添加属性来绕过此行为。为此,我需要获取操作上下文。但是当我注入 IActionContextAccessor 时,属性 ActionContextnull。任何建议如何获取 ActionContext?

public class RefuseUnTrustedHandler : AuthorizationHandler<RefuseUnTrustedRequirement>
{
    private readonly ILogger<RefuseUnTrustedHandler> _logger;
    private readonly IActionContextAccessor _actionContextAccessor;

    public RefuseUnTrustedHandler(
        ILogger<RefuseUnTrustedHandler> logger,
        IActionContextAccessor actionContextAccessor)
    {
        _logger = logger;
        _actionContextAccessor = actionContextAccessor;
    }

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RefuseUnTrustedRequirement requirement)
    {
        // get the custom attributes applied to the action return value
        //var attrs = actionContext.ActionDescriptor
        //              .MethodInfo
        //              .ReturnTypeCustomAttributes
        //              .GetCustomAttributes(typeof(MyCustomAuthorizeAttribute), true)
        //              .OfType<MyCustomAuthorizeAttribute>()
        //              .ToArray();

        // TODO check for Authorize attribute
        if (context.User.Claims.Any(x => x.Type == ClaimTypes.Role && x.Value == Roles.UnTrusted))
        {
            _logger.LogInformation("Request authorization is coming from untrusted source");
            context.Fail();
        }

        context.Succeed(requirement);

        return Task.CompletedTask;
    }
}

0 个答案:

没有答案
相关问题