10

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
});

2 Answers 2

19

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This line options.SecurityTokenValidators.Clear(); save my times. Thanks a lot
How I can return error from Customer token handler - ValidateToken Method?
0

JwtBearerOptions has a parameter named TokenValidationParameters, so you can use this parameter:

var tokenValidationParameters = new TokenValidationParameters
{
    ValidateIssuerSigningKey = true,
    IssuerSigningKey = signingKey,
    //...
};

app.UseJwtBearerAuthentication(new JwtBearerOptions
{
    //...
    TokenValidationParameters = tokenValidationParameters
});

4 Comments

Yea I looked at TokenValidationParameters but couldn't figure out how to do my own token validation. In particular I want to validate the signature and I can't figure out how to do that with TokenValidationParameters.
Are you getting an error? If no what is your token validation logic, could you post it?
I'm not getting an error. There just isn't a TokenHandler property in JwtBearerOptions like there was in JwtBearerAuthenticationOptions.
@Jeremy: Can be done with TokenValidationParameters.SignatureValidator. I've done that, it's working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.