Reputation: 395
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 token. I'm using basic Authentication for JWT
services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(cfg =>
{
cfg.RequireHttpsMetadata = false;
cfg.SaveToken = true;
cfg.TokenValidationParameters = new TokenValidationParameters()
{
ValidAudience = jwtAudience,
ValidIssuer = jwtIssuer,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSecurityKey))
};
});
Is there a way I can add a piece of code to the authorization check that logs if a authorization attempt was valid and why it wasn't?
Upvotes: 13
Views: 22024
Reputation: 1
I was trying to show my "Authorisation" header of the clients requests. It kept showing [redacted]. The appropriate keyword search led me to this article, so here is how it finally worked for me.
services.AddHttpLogging(o =>
{
o.RequestHeaders.Add("Authorization");
});
ofc this is for testing only
Upvotes: 0
Reputation: 81
In addition to Robin Windey
comment I also recommend to use Authorization in appsettings.json
:
"Microsoft.AspNetCore.Authentication": "Information",
"Microsoft.AspNetCore.Authorization": "Information",
Upvotes: 4
Reputation: 426
Not sure if it's already implemented in earlier versions of .NET (Core) but i'm using .NET 6 and i'm able to activate the logging implemented in .NET 6 by setting the loglevel to Information
for to the Microsoft.AspNetCore.Authentication
category.
For example in your appsettings.json
:
"Logging": {
"LogLevel": {
// ...
"Microsoft.AspNetCore.Authentication": "Information"
}
}
This gave me the the following log for an expired token (i'm using log4net with a template):
INFO [Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler] - MESSAGE: Failed to validate the token.
Microsoft.IdentityModel.Tokens.SecurityTokenExpiredException: IDX10223: Lifetime validation failed. The token is expired. ValidTo: 'System.DateTime', Current time: 'System.DateTime'.
at Microsoft.IdentityModel.Tokens.Validators.ValidateLifetime(Nullable`1 notBefore, Nullable`1 expires, SecurityToken securityToken, TokenValidationParameters validationParameters)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateLifetime(Nullable`1 notBefore, Nullable`1 expires, JwtSecurityToken jwtToken, TokenValidationParameters validationParameters)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateTokenPayload(JwtSecurityToken jwtToken, TokenValidationParameters validationParameters)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken& validatedToken)
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
Of course if you want to be more restrictive you could instead use the Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler
category in your appsettings.json
. It's just important to have the loglevel for this class set to Information
since the generated .NET 6 logs have this loglevel.
Upvotes: 18
Reputation: 1726
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.
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,
Upvotes: 26