Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add custom validation to JWT token for ASP.NET Core?

Previously, I was able to use JwtBearerAuthenticationOptions to add my custom token handler with my custom validation. Now with Core UseJwtBearerAuthentication I need to use JwtBearerOptions which doesn't seem to have an option to override JwtSecurityTokenHandler. I basically want to override the following method in JwtSecurityTokenHandler:

protected virtual JwtSecurityToken ValidateSignature(string token, TokenValidationParameters validationParameters)

Previously:

app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
    TokenHandler = new MyTokenHandler()
    // other properties here
});

Currently with ASP.NET Core:

app.UseJwtBearerAuthentication(new JwtBearerOptions
{
    // other properties here
});
like image 891
Jeremy Avatar asked Aug 26 '16 17:08

Jeremy


1 Answers

If you want to actually create your own JwtSecurityTokenHandler and override the ValidateSignature method, you can use the SecurityTokenValidators property:

var options new JwtBearerOptions();
options.SecurityTokenValidators.Clear();
options.SecurityTokenValidators.Add(new MyTokenHandler());
app.UseJwtBearerAuthentication(options);

Technically the call to Clear() isn't necessary - as long as one of the token handlers can parse the token the call to authenticate will succeed. However removing the JwtSecurityTokenHandler seems to make sense if it won't ever succeed in your case.

like image 88
Sock Avatar answered Oct 31 '22 22:10

Sock