I\'m trying to write to a log when I person tries to access a method under an Authorize Attribute. Basically, I want to log if a person uses an invalid token or an expired t
You have access to the JwtBearerEvents object, which defines a number of events that are raised as the bearer token is processed.
OnAuthenticationFailed
Invoked if exceptions are thrown during request processing. The exceptions will be re-thrown after this event unless suppressed.
OnChallenge Invoked before a challenge is sent back to the caller.
OnMessageReceived
Invoked when a protocol message is first received.
OnTokenValidated
Invoked after the security token has passed validation and a ClaimsIdentity has been generated.
https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.jwtbearer.jwtbearerevents?view=aspnetcore-2.0
When initialising the configuration at AddJwtBearer, add the events you'd like to subscribe to,
.AddJwtBearer(o =>
{
o.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = c =>
{
// do some logging or whatever...
}
};
});
Have a look at the source to see when events might be raised,
https://github.com/aspnet/Security/blob/dev/src/Microsoft.AspNetCore.Authentication.JwtBearer/JwtBearerHandler.cs