The wonderful thing about Net Core is that this is built in. You actually dont need to validate the tokens yourself. If the token is invalid, a response is automatically fired back to client for you. IF however, you do feel the need to dive in and manually validate - you can do this: https://www.jerriepelser.com/blog/manually-validating-rs256-jwt-dotnet/
Ok, so i've dug out some code from the bowels of one of my projects.. Basically it lets me hook into the events that occur when a token is validated and assign my own even handlers to various points.
I believe this is what you are looking for.
Add this code to your IServiceCollection registrations:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddCustomJwtBearer(options =>
{
options.TokenValidationParameters = tokenParams;
options.Events = ConfigureJwtEvents(tokenConfiguration);
});
And this code into a STATIC class somewhere so you can call it as an extension method:
public static void AddCustomJwtBearer(this AuthenticationBuilder builder, Action<JwtBearerOptions> options)
{
builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IPostConfigureOptions<JwtBearerOptions>, JwtBearerPostConfigureOptions>());
builder.AddScheme<JwtBearerOptions, JwtBearerHandler>("Bearer", null, options);
}
/// <summary>
/// Returns a configured <see cref="JwtBearerEvents"/>
/// </summary>
/// <param name="tokenConfiguration">Token Configuration</param>
/// <returns><see cref="JwtBearerEvents"/></returns>
private static JwtBearerEvents ConfigureJwtEvents(TokenConfiguration tokenConfiguration)
{
var bearerEvents = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("Token-Expired", "true");
}
return Task.CompletedTask;
}
};
// Authentication Failed Method
bearerEvents.OnAuthenticationFailed = [YOUR-EVENT-HANDLER]
// Challenge Raised Event
bearerEvents.OnChallenge = [YOUR-EVENT-HANDLER]
// Message Received Event
bearerEvents.OnMessageReceived = [YOUR-EVENT-HANDLER]
// Token Validated Event
bearerEvents.OnTokenValidated = [YOUR-EVENT-HANDLER]
return bearerEvents;
}
Where it says: [YOUR-EVENT-HANDLER] .. You can add in your own event handler methods and they will fire if/when each of those events happens.