1

I have an ASP.NET Core Web API. When I set it up, I used the built-in ASP.NET Core identity stuff because that was fast and got me directly into writing the meat of the API functionality. Now I need to be able to log failed logins, but I can't see where to do this.

A class was created automatically at \Overrides\IdentityApiEndpointRouteBuilderExtensions.cs that contains a bunch of identity endpoints, including /login:

routeGroup.MapPost("/login", async Task<Results<Ok<AccessTokenResponse>, EmptyHttpResult, ProblemHttpResult>>
([FromBody] LoginRequest login, [FromQuery] bool? useCookies, [FromQuery] bool? useSessionCookies, [FromServices] IServiceProvider sp) =>
{
    var signInManager = sp.GetRequiredService<SignInManager<TUser>>();

    var useCookieScheme = (useCookies == true) || (useSessionCookies == true);
    var isPersistent = (useCookies == true) && (useSessionCookies != true);
    signInManager.AuthenticationScheme = useCookieScheme ? IdentityConstants.ApplicationScheme : IdentityConstants.BearerScheme;

    var result = await signInManager.PasswordSignInAsync(login.Email, login.Password, isPersistent, lockoutOnFailure: true);

    if (result.RequiresTwoFactor)
    {
        if (!string.IsNullOrEmpty(login.TwoFactorCode))
        {
            result = await signInManager.TwoFactorAuthenticatorSignInAsync(login.TwoFactorCode, isPersistent, rememberClient: isPersistent);
        }
        else if (!string.IsNullOrEmpty(login.TwoFactorRecoveryCode))
        {
            result = await signInManager.TwoFactorRecoveryCodeSignInAsync(login.TwoFactorRecoveryCode);
        }
    }

    if (!result.Succeeded)
    {
        return TypedResults.Problem(result.ToString(), statusCode: StatusCodes.Status401Unauthorized);
    }

    // The signInManager already produced the needed response in the form of a cookie or bearer token.
    return TypedResults.Empty;
});

In my Program.cs in the Main method, I have these lines:

builder.Services.AddAuthorization();
builder.Services.AddIdentityApiEndpoints<IdentityUser>().AddEntityFrameworkStores<DataContext>();

I can't hit breakpoints in that routeGroup.MapPost("/login". In fact, if I remove all of the code from that method, the login still works flawlessly. Obviously, this code is not handling logins.

Where can I find the code that handles these logins so that I can start logging failed logins?

7
  • 2
    A class was created automatically by whom? Identity doesn't generate code. Did you try scaffolding? Run some other tool? Or did you step into the decompiled code using Resharper? That would explain why you can't use breakpoints - that's not actual source code. Commented Oct 1 at 14:51
  • The code you posted is identical to the source code of the MapIdentityApi method, so I suspect there's no generated code. The actual login operation is performed by signInManager.PasswordSignInAsync, not the login handler. .NET infrastructure code already uses the ILogger infrastructure to log events, so the events are probably logged already and hidden due to filters Commented Oct 1 at 14:59
  • Why do you want to log? It matters. In the SigninManager code I see that failures are logged as debug events. That's not unusual - intrusions happen when a hacker logs in successfully, not when a user retries a wrong password. The code also publishes metrics that are far more useful, eg here. If you see an increase in AuthenticateSignIn, something's wrong. Tools like Prometheus can send metric alerts Commented Oct 1 at 15:05
  • 1
    @PanagiotisKanavos I created this application about a year ago and allowed all of the identity stuff to be created automatically when I was creating the project in VisualStudio. I know I did not write those identity routes. I want to log because I have one user who gets 401s, but I can't reproduce them unless I use a bad user or password. I enabled failed request tracing in IIS as well, but I wanted to keep my log in one place. I will try to change the logging level. Thanks! Commented Oct 1 at 15:50
  • 1
    The log filters are probably configures in your appsettings.json, not your code. Even if you change "Default": "Information" to "Default": "Debug" any "Microsoft": "Warning"` or "Microsoft.AspNetCore": "Warning" entries will hide the log entries Commented Oct 1 at 15:57

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.