title: How to Implement Two Factor Authentication Via Email in ASP.Net Core 2?
body: <p>I am using ASP.NET Core 2.2 for a web server, In each time a user login to the website, after entering a correct email &amp; password, I need to send a message containing a <strong>4-digits PIN Code</strong> to user email, to use it as Email Two Factor Authentication, and this PIN Code, <strong>should expire after 10 minutes</strong> after sending it.</p>
  
  <p>I can do this manually (generating random PIN Codes, saving them in Database, verifying them using if statements, etc...), this would work, but I created this question to ask how to do this using ASP.NET Core 2 available features (which can spare the database table for me).</p>
  
  <p>I tried <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.usermanager-1.generatetwofactortokenasync?view=aspnetcore-2.2" rel="noreferrer">UserManager.GenerateTwoFactorTokenAsync(TUser, String) Method</a>, to generate a token and send it to email:</p>
  
  <pre><code>var token = await _userManager.GenerateTwoFactorTokenAsync(user, "Default");
  SendLoginTokenToUserEmail(user, token);
  </code></pre>
  
  <p>and used <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.usermanager-1.verifytwofactortokenasync?view=aspnetcore-2.2" rel="noreferrer">UserManager.VerifyTwoFactorTokenAsync(TUser, String, String)</a> to verify it:</p>
  
  <pre><code>var verified = await _userManager.VerifyTwoFactorTokenAsync(user, "Default", token);
  </code></pre>
  
  <p>This worked perfectly, but my problem was that the generated token wasn't a 4-Digit PIN Code, and its expiration time wasn't 10 minutes (I think the default is 1 day).</p>
  
  <p>So, my Question is: <strong>How to Customize the generated token by UserManager for Two Factor Authentication in ASP.NET Core 2.2?</strong> </p>
  
  <p>Can this done by creating a custom token provider? (I am using Default Token Provider here) if so, what is the steps to do so? I spent hours surfing Docs and ASP.NET Core 2 Articles, but did't find what I need.</p>
  
  <p><em>PS: If there is any other way other than UserManager, I am all ears, but I thought this might be the best way, especially UserManager is used everywhere in our system (for login, password-reset, etc...).</em></p>