自定义AuthorizationHandler HandleRequirementAsync未调用
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义AuthorizationHandler HandleRequirementAsync未调用相关的知识,希望对你有一定的参考价值。
我无法弄清楚为什么我的授权不会成功。
我在研究潜在原因时发现了这一点:
https://github.com/aspnet/Security/issues/1103
似乎OP有类似的问题,尽管我的问题甚至与基于资源的授权无关。
这是我的代码:
AuthorizationHandler:
public class DebugOrDeveloperRequirementHandler : AuthorizationHandler<DebugOrDeveloperRequirement>
{
private readonly IHostingEnvironment _environment;
public DebugOrDeveloperRequirementHandler(IHostingEnvironment environment)
{
// breakpoint here - does get hit
_environment = environment;
}
/// <inheritdoc />
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, DebugOrDeveloperRequirement requirement)
{
// breakpoint here but never hit
if (_environment.IsDevelopment() || _environment.IsIntegrationTest() || context.User.IsInRole(Constants.RoleNames.Developer))
context.Succeed(requirement);
return Task.CompletedTask;
}
}
需求:
public class DebugOrDeveloperRequirement : IAuthorizationRequirement
{
}
Startup.cs代码:
services.AddAuthorization(config =>
{
config.AddPolicy(ApplicationPolicyNames.Contractor, builder =>
{
builder.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser()
.RequireRole(DataLayer.Setup.Constants.RoleNames.Contractor, DataLayer.Setup.Constants.RoleNames.Developer, DataLayer.Setup.Constants.RoleNames.Admin);
});
config.AddPolicy(ApplicationPolicyNames.Customer, builder =>
{
builder.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser()
.RequireRole(DataLayer.Setup.Constants.RoleNames.Customer, DataLayer.Setup.Constants.RoleNames.Developer, DataLayer.Setup.Constants.RoleNames.Admin);
});
config.AddPolicy(ApplicationPolicyNames.Administrator, builder =>
{
builder.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser()
.RequireRole(DataLayer.Setup.Constants.RoleNames.Developer, DataLayer.Setup.Constants.RoleNames.Admin);
});
config.AddPolicy(ApplicationPolicyNames.Developer, builder =>
{
builder.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser()
.RequireRole(DataLayer.Setup.Constants.RoleNames.Developer);
});
config.AddPolicy(ApplicationPolicyNames.DeveloperOrDebug, builder =>
{
builder.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.Requirements.Add(new DebugOrDeveloperRequirement());
});
});
services.AddSingleton<IAuthorizationHandler, DebugOrDeveloperRequirementHandler>();
我的代码与文档看起来并没有什么不同。因此,我无法真正理解为什么不调用AuthorizationHandler。
答案
那么现在我觉得很傻 - 我认为动作授权属性覆盖控制器属性 - 他们没有。
我的控制器有一个开发人员策略 - 在该处理程序执行转向之前使操作失败。
以上是关于自定义AuthorizationHandler HandleRequirementAsync未调用的主要内容,如果未能解决你的问题,请参考以下文章
AuthorizationHandler异常不通过ExceptionFilter
有没有办法在 .Net 5 中的 AuthorizationHandler 中重定向?