title: ASP.NET Web API how to authenticate user
body: <p>I'm trying to create a simple user authentication function but I just can't get it to work.
  Here is the code I'm working on:</p>
  
  <pre><code>public class LoginController : ApiController
  {
      private void SetPrincipal(IPrincipal principal)
      {
          Thread.CurrentPrincipal = principal;
          if (HttpContext.Current != null)
          {
              HttpContext.Current.User = principal;
          }
      }
  
      public bool Login(string token)
      {                       
          //Check token
          if (.....) 
          {
              //Authenticate user
              var identity = new GenericIdentity("Test user");
              SetPrincipal(new GenericPrincipal(identity, new string[]{"Test role"}));
          }
      }
  
      [Authorize]
      public string TestFun()
      {
          return "Hello " + User.Identity.Name;       
      }
  }
  </code></pre>
  
  <p>So, if I try to call method <code>TestFun()</code> first, it returns error code 401 like it should.
  However when I call method <code>Login()</code> it should somehow save user credentials, but this is where I get lost, I just can't get it to work.</p>
  
  <p><code>TestFun()</code> always returns error code 401 even if I call <code>Login()</code> first.
  If I try to put <code>return "Hello " + User.Identity.Name;</code> in the <code>Login()</code> function it returns correct username, but in the <code>TestFun()</code> the user is not available.</p>
  
  <p>I've even tried using Sessions and FormsAuthentication but I just can't get it to work, even on this really simple example.</p>
  
  <p>Can someone please tell me what am I missing?</p>
  
  <p>Thanks!</p>