我有一个案例,我想要使用 Bearer 令牌进行身份验证和 Basic 身份验证,但是每次使用 Basic 时我都会收到 403 Forbidden ([Authorize(AuthenticationSchemes = "BasicAuthentication")])。
. 这是我的startup.cs:
services
.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(cfg =>
{
cfg.RequireHttpsMetadata = false;
cfg.SaveToken = true;
cfg.TokenValidationParameters = new TokenValidationParameters
{
...
};
})
.AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);
services.AddAuthorization(options =>
{
options.AddPolicy("BasicAuthentication",
authBuilder =>
{
authBuilder.AddAuthenticationSchemes("BasicAuthentication");
authBuilder.RequireClaim("NameIdentifier");
});
});
我为 Basic 添加了一个处理程序:
public class BasicAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (!Request.Headers.ContainsKey("Authorization"))
return AuthenticateResult.Fail("Missing Authorization Header");
...
var claims = new[] {
new Claim(ClaimTypes.NameIdentifier, username),
new Claim(ClaimTypes.Role, "User"),
new Claim(ClaimTypes.Name, username)
};
var identity = new ClaimsIdentity(claims, Scheme.Name);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, Scheme.Name);
return AuthenticateResult.Success(ticket);
}
}
处理程序在正确的情况下返回 Success,但仍返回 403。