title: How to implement two factor auth in Web API 2 using ASP.NET identity?
body: <p>I have seen this link <a href="http://bitoftech.net/2014/10/15/two-factor-authentication-asp-net-web-api-angularjs-google-authenticator/" rel="noreferrer">Two Factor Auth using goolgle authenticator</a> on how to create a two factor authentication in web api, but my requirements are little different. </p>
  
  <ol>
  <li>I want to use two factor authentication for issuing an access token. (If the user has chosen to enable two factor authentication)</li>
  <li>I would like to create the OTP code using ASP.NET identity itself. (Like the way we do in MVC web application <code>SignInManager.SendTwoFactorCodeAsync("Phone Code")</code></li>
  </ol>
  
  <p>The problem with my current implementation is, when I call <code>SignInManager.SendTwoFactorCodeAsync("Phone Code")</code> I get the error user id not found. </p>
  
  <p>To debug, I tried calling <code>User.Identity.GetUserId();</code> and it returns the correct user id. </p>
  
  <p>I checked the source code of Microsoft.AspNet.Identity.Owin assembly </p>
  
  <pre><code>    public virtual async Task&lt;bool&gt; SendTwoFactorCodeAsync(string provider)
      {
          var userId = await GetVerifiedUserIdAsync().WithCurrentCulture();
          if (userId == null)
          {
              return false;
          }
  
          var token = await UserManager.GenerateTwoFactorTokenAsync(userId, provider).WithCurrentCulture();
          // See IdentityConfig.cs to plug in Email/SMS services to actually send the code
          await UserManager.NotifyTwoFactorTokenAsync(userId, provider, token).WithCurrentCulture();
          return true;
      }
  
      public async Task&lt;TKey&gt; GetVerifiedUserIdAsync()
      {
          var result = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.TwoFactorCookie).WithCurrentCulture();
          if (result != null &amp;&amp; result.Identity != null &amp;&amp; !String.IsNullOrEmpty(result.Identity.GetUserId()))
          {
              return ConvertIdFromString(result.Identity.GetUserId());
          }
          return default(TKey);
      }
  </code></pre>
  
  <p>As seen from the above code, <code>SendTwoFactorCodeAsync</code> method internally calls <code>GetVerifiedUserIdAsync</code> which checks the two factor authentication cookie. As this is a web api project, cookie isn't there and 0 is returned, resulting in user id not found error.</p>
  
  <p>My question, how to correctly implement two factor authentication in web api using asp.net identity? </p>