Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 410
user2850818 Avatar asked Feb 20 '18 16:02

user2850818


1 Answers

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

like image 119
Dylan Morley Avatar answered Sep 23 '22 13:09

Dylan Morley