How do I log authorization attempts in .net core

前端 未结 1 539
忘了有多久
忘了有多久 2021-01-12 04:13

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

1条回答
  •  被撕碎了的回忆
    2021-01-12 04:27

    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

    0 讨论(0)
提交回复
热议问题