title: How to use Api key in Web Api for service authentication using forms authentication
body: <p>I am using MVC 4 Web Api and I want the users to be authenticated, before using my service.</p>
  
  <p>I have implemented an authorization message handler, that works just fine.</p>
  
  <pre><code>public class AuthorizationHandler : DelegatingHandler
  {
      private readonly AuthenticationService _authenticationService = new AuthenticationService();
  
      protected override Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
      {
          IEnumerable&lt;string&gt; apiKeyHeaderValues = null;
          if (request.Headers.TryGetValues("X-ApiKey", out apiKeyHeaderValues))
          {
              var apiKeyHeaderValue = apiKeyHeaderValues.First();
  
              // ... your authentication logic here ...
              var user = _authenticationService.GetUserByKey(new Guid(apiKeyHeaderValue));
  
              if (user != null)
              {
  
                  var userId = user.Id;
  
                  var userIdClaim = new Claim(ClaimTypes.SerialNumber, userId.ToString());
                  var identity = new ClaimsIdentity(new[] { userIdClaim }, "ApiKey");
                  var principal = new ClaimsPrincipal(identity);
  
                  Thread.CurrentPrincipal = principal;
              }
          }
  
          return base.SendAsync(request, cancellationToken);
      }
  }
  </code></pre>
  
  <p>The problem is, that I use forms authentication.</p>
  
  <pre><code>[HttpPost]
      public ActionResult Login(UserModel model)
      {
          if (ModelState.IsValid)
          {
              var user = _authenticationService.Login(model);
              if (user != null)
              {
                  // Add the api key to the HttpResponse???
              }
              return View(model);
          }
  
          return View(model);
      }
  </code></pre>
  
  <p>When I call my api:</p>
  
  <pre><code> [Authorize]
  public class TestController : ApiController
  {
      public string GetLists()
      {
          return "Weee";
      }
  }
  </code></pre>
  
  <p>The handler can not find the X-ApiKey header.</p>
  
  <p>Is there a way to add the user's api key to the http response header and to keep the key there, as long as the user is logged in?
  Is there another way to implement this functionality?</p>