【发布时间】:2020-02-08 11:22:49
【问题描述】:
我创建了一个默认的 ASP.NET Core (2.1) 空 Web 应用程序,并添加了 JWT 不记名身份验证。 Startup.cs 类如下所示:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
var keyByteArray = Convert.FromBase64String(Constants.JwtSecretKey);
var signinKey = new SymmetricSecurityKey(keyByteArray);
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = true,
ValidAudience = Constants.Audience,
ValidateIssuer = true,
ValidIssuer = Constants.Issuer,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = signinKey
};
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
app.UseMvc();
}
控制器如下所示:
[Route("values")]
[ApiController]
public class ValuesController : Controller
{
[HttpGet("")]
public IActionResult Get()
{
return new StatusCodeResult(StatusCodes.Status200OK);
}
}
我希望我的端点在授权标头存在但无效(带有包含失败原因的错误消息)时返回 401 HTTP 状态代码 - 但在标头丢失时不返回。可以这样配置中间件吗?
我尝试处理来自 JwtBearerEvents 的 OnAuthenticationFailed 事件,但无法完成任何操作。
options.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = context =>
{
// Not fired when the Authorization header is "Bearer foo",
// but fired when the header is "Bearer foo.bar.baz"
return Task.CompletedTask;
}
};
【问题讨论】:
标签: c# asp.net-core jwt