为ASP.NET Core的JWT令牌添加自定义验证?

Jer*_*emy 5 c# authentication jwt openid-connect asp.net-core

以前,我可以使用JwtBearerAuthenticationOptions自定义验证添加自定义令牌处理程序.现在使用Core UseJwtBearerAuthentication我需要使用JwtBearerOptions哪个似乎没有覆盖选项JwtSecurityTokenHandler.我基本上想要覆盖以下方法JwtSecurityTokenHandler:

protected virtual JwtSecurityToken ValidateSignature(string token, TokenValidationParameters validationParameters)
Run Code Online (Sandbox Code Playgroud)

先前:

app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
    TokenHandler = new MyTokenHandler()
    // other properties here
});
Run Code Online (Sandbox Code Playgroud)

目前使用ASP.NET Core:

app.UseJwtBearerAuthentication(new JwtBearerOptions
{
    // other properties here
});
Run Code Online (Sandbox Code Playgroud)

Soc*_*ock 10

如果您想实际创建自己JwtSecurityTokenHandlerValidateSignature方法并覆盖该方法,可以使用该SecurityTokenValidators属性:

var options new JwtBearerOptions();
options.SecurityTokenValidators.Clear();
options.SecurityTokenValidators.Add(new MyTokenHandler());
app.UseJwtBearerAuthentication(options);
Run Code Online (Sandbox Code Playgroud)

从技术上讲,调用Clear()是不必要的 - 只要其中一个令牌处理程序可以解析令牌,对authenticate的调用就会成功.然而,JwtSecurityTokenHandler如果它在你的情况下不会成功,那么删除似乎是有意义的.