Koli96
Koli96

Reputation: 79

How to log unathorized access tries

I have .Net Core 2.1 application and I have added JWT Authorization

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(o =>
            {
                ...
            });

How can I log tries to access actions with [Authorize] attribute? I treid to use this method https://stackoverflow.com/a/46963194/7137259 and inject my Logger, but my logger uses Entity DB Context, and I can't inject scoped Logger to IConfigureNamedOptions. Also how can I return normal response when Unauthorized?

Upvotes: 1

Views: 181

Answers (1)

Alex Riabov
Alex Riabov

Reputation: 9175

You can resolve your scoped service in JwtBearerEvents, you can modify the response there as well:

.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, o =>
{
    o.Events = new JwtBearerEvents()
    {
        OnAuthenticationFailed = c =>
        {
            var svc = c.HttpContext.RequestServices.GetRequiredService<IMyService>();
            c.NoResult();
            c.Response.StatusCode = 500;
            c.Response.ContentType = "text/plain";
            c.Response.WriteAsync(c.Exception.ToString()).Wait();
            return Task.CompletedTask;
        }
    };
});

Upvotes: 2

Related Questions