简体   繁体   中英

How do I log authorization attempts in .net core

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM