我遇到了奇怪的问题,无法进行调试。
我正在尝试使用OperationAuthorizationRequirement
和AuthorizationHandler
。
当我在控制器中设置断点时,我始终得到403结果,所以我尝试在CountryControllerAuthorizationHandler
内部设置断点,但它从来没有被触发。但是在控制器中,我总是得到AuthorizeAsync false
的结果,但我不明白为什么不能命中或触发断点。我犯了一些愚蠢的错误吗?无论如何,据我所见,资源不为空
,用户和声明也是不为空
:
下面是我的代码:
CountryControllerAuthorizationHandler:
public class CountryControllerAuthorizationHandler : AuthorizationHandler<OperationAuthorizationRequirement, Country>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
OperationAuthorizationRequirement requirement,
Country resource)
{
if (requirement.Name == Operations.ReadDetail.Name &&
context.User.Claims.FirstOrDefault(a => a.Type == "userType")?.Value == "customer"
)
{
context.Succeed(requirement);
}
if (requirement.Name == Operations.Create.Name &&
context.User.Claims.FirstOrDefault(a => a.Type == "userType")?.Value == "1"
)
{
context.Succeed(requirement);
}
if (requirement.Name == Operations.Update.Name &&
context.User.Claims.FirstOrDefault(a => a.Type == "userType")?.Value == "1"
)
{
context.Succeed(requirement);
}
if (requirement.Name == Operations.Delete.Name &&
context.User.Claims.FirstOrDefault(a => a.Type == "userType")?.Value == "1"
)
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
操作类:
public static class Operations
{
public static OperationAuthorizationRequirement Create =
new OperationAuthorizationRequirement { Name = nameof(Create) };
public static OperationAuthorizationRequirement Read =
new OperationAuthorizationRequirement { Name = nameof(Read) };
public static OperationAuthorizationRequirement ReadDetail =
new OperationAuthorizationRequirement { Name = nameof(ReadDetail) };
public static OperationAuthorizationRequirement Update =
new OperationAuthorizationRequirement { Name = nameof(Update) };
public static OperationAuthorizationRequirement Delete =
new OperationAuthorizationRequirement { Name = nameof(Delete) };
}
Startup.cs:
services.AddSingleton<IAuthorizationHandler, CountryControllerAuthorizationHandler>();
services.AddMvcCore()
.AddAuthorization()
.AddJsonFormatters();
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.ApiName = "api1";
});
最后是控制器:
public CountriesController(ICountryService service, IAuthorizationService authorizationService)
{
_authorizationService = authorizationService;
this.countryService = service;
}
public async Task<object> GetDetail()
{
var obj = countryService.Get_DETAILS();
var authorizationResult = await _authorizationService.AuthorizeAsync(User, obj, Operations.ReadDetail);
if (authorizationResult.Succeeded)
{
return Ok(obj);
}
else if (User.Identity.IsAuthenticated)
{
return new ForbidResult();
}
else
{
return new ChallengeResult();
}
}
AuthorizeAsync
调用中获得失败的结果。但是在您的授权处理程序内部没有触发断点?countryService.Get_DETAILS()
返回什么类型?这是您用于授权处理程序的相同“Country”类型吗? - poke