【发布时间】:2017-12-26 22:31:15
【问题描述】:
我不知道为什么我的授权不会成功。
我在调查潜在原因时发现了这一点:
https://github.com/aspnet/Security/issues/1103
似乎 OP 也有类似的问题,尽管我的问题甚至与基于资源的授权无关。
这是我的代码:
授权处理程序:
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。
【问题讨论】:
标签: c# asp.net-core authorization