【发布时间】:2019-11-29 05:48:28
【问题描述】:
问题陈述
当我向健康端点发送 GET 请求时,本地部署的 dotnet core MVC 应用返回 403 Forbidden,表明用户已通过身份验证但无权使用该资源。
问题
- 我是否需要在 Auth0 中设置用户和角色才能使其正常工作?
- 除了我在下面提供的代码之外,dotnet core 基于策略的授权是否需要额外的代码?
- 由于 ScopeHandler 异步处理需求,我的控制器操作是否需要异步?
目前使用的资源
Auth0 tutorial for dotnet core Authorization
相关代码
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
string domain = $"https://{Configuration["Auth0:domain"]}/";
services.AddAuthentication(opts => {
opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
opts.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(opts => {
opts.Authority = domain;
opts.Audience = Configuration["Auth0:Identifier"];
opts.RequireHttpsMetadata = false;
});
services.AddAuthorization(options =>
{
options.AddPolicy("check:health", policy => policy.Requirements.Add(new HasScopeRequirement("check:health", domain)));
});
services.AddSingleton<IAuthorizationHandler, ScopeHandler>();
services.AddDbContext<PathosContext>(
options => options.UseSqlite(Configuration["PathosConnectionString"])
);
}
HasScopeRequirement.cs
public class HasScopeRequirement : IAuthorizationRequirement
{
public string Issuer { get; }
public string Scope { get; }
public HasScopeRequirement(string scope, string issuer)
{
Scope = scope ?? throw new ArgumentNullException(nameof(scope));
Issuer = issuer ?? throw new ArgumentNullException(nameof(issuer));
}
}
ScopeHandler.cs
public class ScopeHandler : AuthorizationHandler<HasScopeRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, HasScopeRequirement requirement)
{
if (!context.User.HasClaim(c => c.Type == "scope" && c.Issuer == requirement.Issuer))
return Task.CompletedTask;
var scopes = context.User.FindFirst(c => c.Type == "scope" && c.Issuer == requirement.Issuer).Value.Split(' ');
if (scopes.Any(s => s == requirement.Scope))
context.Succeed(requirement);
return Task.CompletedTask;
}
}
HealthController.cs
public class HealthController: Controller
{
[Authorize("check:health")]
[HttpGet]
public IActionResult Index() {
return Ok("healthy");
}
}
步骤
- 从
[Authorize]注释中删除范围/权限。结果:按预期返回 200 OK - 将
context.Succeed(requirement);和return Task.CompletedTask移动到HandleRequirementAsync方法的顶部。 RESULT 200 OK 响应按预期返回。
【问题讨论】: