'How to handle the UserNotConfirmedException during AWS Cognito's login process in ASP.net core?

I'm using the official AWS Cognito sample to integrate Cognito in an asp.net Core MVC application and I'm wondering how I can handle the UserNotConfirmedException to confirm the user's e-mail address via the code that was received by e-mail.

Indeed, the sample seems to only confirm the account during the registration process but, what if the user was created by an admin in the AWS console, or via an API: this case should be handled during the login method.
So, this line raises an UserNotConfirmedException exception so I catch it as follows:

        catch(Exception e)
        {
            if ((e is UserNotConfirmedException) || (e.InnerException is UserNotConfirmedException))
            {
                _logger.LogWarning("User needs to enter email confirmation code");
                return RedirectToPage("./ConfirmAccount");
            }
        }

This redirects to ConfirmAccountModel.OnPostAsync but this line raises "NullReferenceException: Object reference not set to an instance of an object", because user hasn't been signed in yet and User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name) is null.

So my question is: how can I handle the case when a user needs to verify his email and enter a code during the login process ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source