Search code examples
.net-coreasp.net-identityidentityasp.net-core-2.2.net-core-2.2

SignInResult.RequiresTwoFactor always return false


In my dotnet core 2.2 application I am trying to enable two factor authentication. In the startup class I have created a seed data function that will generate a sample user. I use UserManager to create the user and then set the two factor required flag. But when the user signs in it always succeeds and never reaches the RequireTwoFactor flag if statement.

I'm pretty sure that I am missing something in my startup class.

All help is appreciated.

startup class Configure method

services.AddIdentity<IdentityUser, IdentityRole>(options =>
{
    options.Tokens.AuthenticatorTokenProvider = "email";
});

seed data method

var User = new IdentityUser() { UserName = email, Email = email };
await UserManager.CreateAsync(User, password);
await UserManager.SetTwoFactorEnabledAsync(User, true);

sign in page

if (ModelState.IsValid)
{
    var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);
    if (result.Succeeded)
    {
        _logger.LogInformation("User logged in.");
        return LocalRedirect(returnUrl);
    }
    if (result.RequiresTwoFactor)
    {
        return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
    }
    if (result.IsLockedOut)
    {
        _logger.LogWarning("User account locked out.");
        return RedirectToPage("./Lockout");
    }
    else
    {
        ModelState.AddModelError(string.Empty, "Invalid login attempt.");
        return Page();
    }
}

Solution

  • I have had the same problem.

    Today I updated to .net core 3.0.100-rc1-014190 and the problem is resolved. So if the 'TwoFactorEnabled' flag is set in the ASPNetUsers table PasswordSignInAsync will return the result with RequiresTwoFactor