Search code examples
c#asp.net-coreasp.net-core-identityasp.net-identity-2

ASP.NET Core Identity Enable Authenticator page


I just scaffolded ASP.NET Core Identity pages in Visual Studio 2022. Now I am going through the EnableAuthenticator.cshtml page but I am not able to understand the code. This page should only be visible once and once the authenticator has been setup the user should not be able to access this page at all.

This is the code for it when the page loads. After spending 1 hour stackoverflow keeps complaining of unformatted code even though it is properly formatted so I am attaching in text below:

public async Task<IActionResult> OnGetAsync()
{
    var user = await _userManager.GetUserAsync(User);

    if (user == null)
    {
        return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
    }

    await LoadSharedKeyAndQrCodeUriAsync(user);
    return Page();
}

So basically in this function OnGetAsync, I do not see any code which states that this page should be forbidden once 2FA has been setup. Basically even a hacker can visit this page and add it to the authenticator. I think this sample scaffolded code has a big bug.

Could you please help me with it on how to avoid this page once it has been setup?


Solution

  • I don't think this is a bug, it's just that you need such a feature in your requirements, and you can modify the method below to achieve it.

    public async Task<IActionResult> OnGetAsync()
    {
        var user = await _userManager.GetUserAsync(User);
        if (user == null)
        {
            return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
        }
        if (!user.TwoFactorEnabled)
        {
            await LoadSharedKeyAndQrCodeUriAsync(user);
    
            return Page();
        }
        else {
            // Something like this
            return NotFound();
        } 
    }
    

    Why don't I think it's not a bug, because after enabling the feature, you may want to turn off the verification of this 2FA in the future, assuming that there is only this one enabled entry, the user experience will be very unfriendly.