title: ASP.NET Identity in a Web API
body: <p>I am working on a simple application that uses the new ASP.NET Identity for authentication. Since I plan to have a mobile app in the future, I have placed the authentication in a Web API, which I post to from jQuery from a Razor Web Page (no MVC or Forms). So far, post works fine and creates users and logs them in - on the API side.</p>
  
  <p>However, I am unable to determine how to proceed from there. I need to set IsAuthenticated so that I can serve up the right pages but it always returns false. Since Identity is extremely new, there is very little documentation available for it and I am unable to locate anything as complex as running it from a Web API. </p>
  
  <p><strong>Q: What is the correct way to return from Identity authentication in a Web API after logging in so that <code>User.Identity.IsAuthenticated</code> gets set correctly?</strong></p>
  
  <p>Login.cshtml</p>
  
  <pre><code>@if (User.Identity.IsAuthenticated)
  {
      @RenderPage("/userpage.cshtml");
  }
  
  else
  {
      &lt;form id="loginForm"&gt;
          &lt;b&gt;Login&lt;/b&gt;
          &lt;input type="email" placeholder="Email" name="email" id="loginEmail" /&gt;
          &lt;input type="password" placeholder="Password" name="password" id="loginPassword" /&gt;
          &lt;input type="submit" value="Log In"/&gt;
      &lt;/form&gt;
   }
  
  &lt;script&gt;
      $("#loginForm").submit(function(event)
      {
          event.preventDefault();
          $.post("/api/login/",
          {
              Username: $('#loginEmail').val(),
              Password: $('#loginPassword').val()
          }, function () 
             { 
                 //???
             }, "json");
  
          return false;
      });
  &lt;/script&gt;
  </code></pre>
  
  <p>Login Web API</p>
  
  <pre><code>public class LoginController : ApiController
  {
      public async void Post(UserInfo info)
      {
          var manager = new AuthenticationIdentityManager(new IdentityStore());
          var result = await manager.Authentication.CheckPasswordAndSignInAsync(HttpContext.Current.GetOwinContext().Authentication, info.Username, info.Password, true);
  
          if (result.Success)
          {
              //???
          }
      }
  }
  </code></pre>