[英]ASP.NET Core Authorization Policies: Can't step into the handler?
我在我的.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从容器中解析所有这些处理程序并尝试匹配特定要求。 由于没有注册这样的处理程序 - 没有设置context.Succeed
和整个授权失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.