C#-ASP.NET Core授权策略:无法进入处理程序?

我在.NET Core应用程序中设置了基于JWT的声明身份验证/授权,该身份验证按预期进行了身份验证,但是我的策略实施未达到我的预期.

我有一个需求实现和处理程序,设置如下:

public class ImpersonationRequirement : IAuthorizationRequirement
{
}

public class ImpersonationHandler : AuthorizationHandler<ImpersonationRequirement>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
        ImpersonationRequirement requirement)
    {
        if (context.User.CanImpersonate()) context.Succeed(requirement);

        return Task.CompletedTask;
    }
}

我有一个这样的助手:

public static bool CanImpersonate(
    this ClaimsPrincipal principal)
{
    var val = principal?.FindFirst(MyClaimTypes.CAN_IMPERSONATE)?.Value;
    return bool.TryParse(val, out var value) && value;
}

public class MyClaimTypes
{
    /// <summary>
    /// Boolean value indicating this user is authorized to impersonate other customer accounts.
    /// </summary>
    public const string CAN_IMPERSONATE = "cim";

    ...

    /// <summary>
    /// Actual name of the user impersonating the current user.
    /// </summary>
    public const string IMPERSONATING_USER = "imp";
}

…从我的Startup.cs开始,我已定义了策略:

services.AddAuthorization(options =>
{
    options.AddPolicy("Impersonator", policy => policy.Requirements.Add(new ImpersonationRequirement()));
});

…在我的控制器上这样写:

[Produces("application/json")]
[Authorize(Policy = "Impersonator")]
public class ImpersonationController : Controller
{
    private readonly ILogger _logger;
    private readonly ITokenManagementService _tokenManagementService;
    private readonly UserManager<MyUser> _userManager;

    public ImpersonationController(ITokenManagementService tokenManagementService, ILoggerFactory loggerFactory, UserManager<MyUser> userManager)
    {
        _tokenManagementService = tokenManagementService;
        _userManager = userManager;
        _logger = loggerFactory.CreateLogger<ImpersonationController>();
    }

    [HttpPost]
    [Route("~/api/impersonation/token")]
    [ProducesResponseType(typeof(AuthenticationResponse), 200)]
    [ProducesResponseType(typeof(Exception), 500)]
    public async Task<IActionResult> Impersonate([FromBody] string userNameToImpersonate)
    {
        try
        {
            var impersonated = await _userManager.FindByNameAsync(userNameToImpersonate);
            if (impersonated == null) throw new EntityNotFoundException($"Unable to find user '{userNameToImpersonate}' in the data store.");
            var actualUserId = User.UserId();
            var token = await _tokenManagementService.GenerateJwt(impersonated.Id, actualUserId);
            var refresh = await _tokenManagementService.GenerateRefreshToken(impersonated.Id, actualUserId);
            var response = new AuthenticationResponse {AuthenticationToken = token, RefreshToken = refresh};
            return Ok(response);
        }
        catch (Exception ex)
        {
            return new OopsResult(ex);
        }
    }
}

如果在注释掉AuthorizeAttribute的情况下运行此程序,则可以查看用户的声明,并且声明枚举中包含“ cim:true”,但是如果在启用AuthorizeAttribute的情况下运行它,则会收到403 Forbidden错误.

我尝试在ImpersonationHandler的行上放置一个断点:

if (context.User.CanImpersonate()) context.Succeed(requirement);

…但是调试器永远不会在这里停止,所以我不知道问题出在哪里.有人可以教育我关于我做错了什么吗?

解决方法:

看来您忘记了在DI容器中注册ImpersonationHandler(这确实很容易忘记):

services.AddSingleton<IAuthorizationHandler, ImpersonationHandler>();

Asp.net从容器解析所有此类处理程序,并尝试匹配特定要求.由于未注册任何此类处理程序-不会设置上下文.成功且整个授权失败.

上一篇:python-金字塔:为什么不能在没有授权策略的情况下使用身份验证策略?


下一篇:Google Maps Android v2授权失败