我正在编写一个小型授权服务,它将使用Net Core 1.1进行基本身份验证和JWT授权。我带了Barry Dorans'示例作为基本身份验证中间件的基础。问题是,有时我的服务将接收没有授权标头的请求,在这种情况下,我想允许以[AllowAnonymous]标记的操作。
这是授权工作ConfigureServices
的一部分:
_services.AddAuthorization(o =>
{
ClaimOptions authenticatedClaimOptions = new ClaimOptions(CustomClaimTypes.AUTHENTICATED, true);
o.AddPolicy(Policies.AUTHENTICATED, p => p.RequireClaim(authenticatedClaimOptions.ClaimType, authenticatedClaimOptions.ClaimValue));
ClaimOptions tenantMemberClaimOptions = new ClaimOptions(CustomClaimTypes.TENANT_MEMBER, true);
o.AddPolicy(Policies.TENANT_MEMBER, p => p.RequireClaim(tenantMemberClaimOptions.ClaimType, tenantMemberClaimOptions.ClaimValue));
});
_services.AddMvcCore(c =>
{
AuthorizationPolicy policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
c.Filters.Add(new AuthorizeFilter(policy));
// if I uncomment the next line all actions will work as if marked with [AllowAnonymous]
//c.Filters.Add(new AllowAnonymousFilter());
})
.AddApiExplorer()
.AddJsonFormatters(s =>
{
s.ContractResolver = new CamelCasePropertyNamesContractResolver();
s.NullValueHandling = NullValueHandling.Ignore;
});
这是我的Configure
方法的一部分:
var baeh = new BasicAuthenticationEventHandler(loggerFactory.CreateLogger<BasicAuthenticationEventHandler>(), _configurationRoot, securityOptions);
app.UseBasicAuthenticationMiddleware(new BasicAuthenticationOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
Events = new BasicAuthenticationEvents
{
OnValidateCredentials = baeh.ValidateCredentialsHandler,
OnAuthenticationFailed = baeh.AuthenticationFailedHandler
}
});
app.UseJwtBearerAuthentication(new JwtBearerOptions()
{
AutomaticAuthenticate = false,
AutomaticChallenge = false,
TokenValidationParameters = jwtParameters,
SaveToken = true
});
在HandleAuthenticateAsync
我没有检测到授权标头时我正在AuthenticateResult.Skip()
,因此期望BasicAuthenticationMiddleware和JwtBearerMiddleware跳过身份验证并最终进入我的[AllowAnonymous]
操作。但每次没有标题时,我最终都在我的BasicAuthenticationMiddleware的HandleUnauthorizedAsync
处理程序中。请有人解释一下,为什么。到目前为止,我已经完成了所有想法。
谢谢你的任何建议。