Search code examples
c#.nettwo-factor-authentication

Two factor auth: when use code always getting null from GetTwoFactorAuthenticationUserAsync


I'm trying to implement two-factor authentication on net 5 web app.

var twoFactorCodeToken = await _userManager.GenerateTwoFactorTokenAsync(user, "Email");

Code is successfully generated and delivered to email.

When I use that generated two factor code in the handler

var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();

I'm getting user as null.

Settings on the Startup

services.AddIdentity<User, IdentityRole>(options =>
{
   ...
   options.Tokens.EmailConfirmationTokenProvider = "emailconfirmation";
   options.Lockout.AllowedForNewUsers = true;            
}).AddEntityFrameworkStores<MyDbContext>()
  .AddDefaultTokenProviders()
  .AddTokenProvider<EmailConfirmationTokenProvider<User>>("emailconfirmation");

services.Configure<DataProtectionTokenProviderOptions>(opt => opt.TokenLifespan = TimeSpan.FromHours(2));
services.Configure<EmailConfirmationTokenProviderOptions>(opt => opt.TokenLifespan = TimeSpan.FromDays(3));

public class EmailConfirmationTokenProviderOptions : DataProtectionTokenProviderOptions
{
}

Am I missing something here?


Solution

  • You need to call PasswordSignInAsync first. If user requires Two Factor Authetnication special cookie will be set which will be used by GetTwoFactorAuthenticationUserAsync