Search code examples
c#authentication.net-coreoauth-2.0asp.net-identity-3

Is There A Way to Get Identity of User on Failed ASP.NET Core Remote Authentication?


I am making use of ASP.NET Core (.NET7)'s remote authentication API for my application's identity. This means users authenticate with Google, Microsoft, or Twitter to authenticate with my application.

My users also have an email address, but passwords are not used/maintained by my application. Identity is associated strictly with a remote authentication provider, and this has worked really well for several years now with very few problems.

However, one primary challenge with this setup is that the remote provider (e.g. Twitter/X) may ban the user for violating content policies. This means they can no longer authenticate with my application.

What I would like to do is detect this event (i.e., a 403 on sign-in) and send an email to the user's address so that they can click it and begin the process of associating with another provider.

I have all my remote authenticators configured in the following manner:

services.AddAuthentication()
        .AddTwitter(x => x.Events.OnRemoteFailure
                          = y =>
                            {
                                if (y.Failure is HttpRequestException request)
                                {
                                    switch (request.StatusCode)
                                    {
                                        case HttpStatusCode.Forbidden:
                                            // How to get the failed user identity?
                                            break;
                                    }
                                }
                                return Task.CompletedTask;
                            });

Where y is a RemoteFailureContext. When a 403 error occurs, I have difficulty determining the user who attempted the sign-in By this point, the user has provided correct and valid credentials to the remote authenticator, and the remote authenticator has determined the status of this account to be suspended, resulting in the 403.

Is there a way to retrieve the user identity of the failed sign-in at this time?


Solution

  • I would not expect an external authentication provider to provide user information after they've been suspended/banned. Even if some might (which I think is bad practice), it's likely to vary between providers.

    I would take a generic approach to this - if a user has trouble authenticating with one of these providers, just provide them the option to enter their email to start an account recovery process.