要在ASP.NET Core 3.1中使用AddJwtBearer,并在验证失败时触发OnTokenValidated事件,可以按照以下步骤进行操作:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
// 设置验证密钥
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key")),
// 设置验证参数
ValidateIssuer = true,
ValidateAudience = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "your_issuer",
ValidAudience = "your_audience",
// 设置事件处理程序
Events = new JwtBearerEvents
{
OnTokenValidated = context =>
{
// 在验证成功时执行的逻辑
// 可以在这里添加自定义消息
if (context.SecurityToken != null)
{
// 添加自定义消息
context.Fail("Custom error message");
}
return Task.CompletedTask;
},
OnAuthenticationFailed = context =>
{
// 在验证失败时执行的逻辑
// 可以在这里添加自定义消息
if (context.Exception != null)
{
// 添加自定义消息
context.Fail("Custom error message");
}
return Task.CompletedTask;
}
}
};
});
app.UseAuthentication();
这样,当验证失败时,OnTokenValidated或OnAuthenticationFailed事件会触发,并且可以在事件处理程序中添加自定义错误消息。