title: ASP.NET Web Api with OWIN - Custom authentication
body: <p>I'm trying to create a new API Key custom authentication provider to plug into my OWIN pipeline.
  I'm using Cookie, OAuth and ADFS providers as well.
  The code I've implemented is pretty much this:</p>
  
  <pre><code>public static class ApiKeyAuthenticationExtension
  {
      public static IAppBuilder UseApiKeyAuthentication(this IAppBuilder appBuilder, ApiKeyAuthenticationOptions options = null)
      {
          appBuilder.Use&lt;ApiKeyAuthenticationMiddleware&gt;(options ?? new ApiKeyAuthenticationOptions("ApiKey"));
          appBuilder.UseStageMarker(PipelineStage.Authenticate);
  
          return appBuilder;
      }
  }
  
  public class ApiKeyAuthenticationMiddleware : AuthenticationMiddleware&lt;AuthenticationOptions&gt;
  {
      public ApiKeyAuthenticationMiddleware(OwinMiddleware next, AuthenticationOptions options) : base(next, options)
      {
      }
  
      protected override AuthenticationHandler&lt;AuthenticationOptions&gt; CreateHandler()
      {
          return new ApiKeyAuthenticationHandler();
      }
  }
  
  public class ApiKeyAuthenticationHandler : AuthenticationHandler&lt;AuthenticationOptions&gt;
  {
      private const string ApiKey = ".....";
  
      protected override Task&lt;AuthenticationTicket&gt; AuthenticateCoreAsync()
      {
          string apiKey = Context.Request.Headers["ApiKey"];
          if (!string.IsNullOrEmpty(apiKey) &amp;&amp; ApiKey.Equals(apiKey))
          {
              var identity = new ClaimsIdentity(Options.AuthenticationType);
              identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "Id", null, Options.AuthenticationType));
              identity.AddClaim(new Claim(ClaimTypes.Name, "Name"));
              identity.AddClaim(new Claim(ClaimTypes.Email, "bla@blu.com"));
  
              return new Task&lt;AuthenticationTicket&gt;(() =&gt; new AuthenticationTicket(identity, new AuthenticationProperties()));
          }
  
          return Task.FromResult(null as AuthenticationTicket);
      }
  }
  
  public class ApiKeyAuthenticationOptions : AuthenticationOptions
  {
      public ApiKeyAuthenticationOptions(string authenticationType) : base(authenticationType)
      {
      }
  }
  </code></pre>
  
  <p>My Startup.Auth looks like this:</p>
  
  <pre><code>app.UseCookieAuthentication(...
  app.UseActiveDirectoryFederationServicesBearerAuthentication(...
  app.UseOAuthAuthorizationServer(...
  app.UseOAuthBearerAuthentication(...
  </code></pre>
  
  <p>and at the end</p>
  
  <pre><code>app.UseApiKeyAuthentication(...
  </code></pre>
  
  <p>When the execution goes into AuthenticateCoreAsync and I return and authentication ticket, the browser just hangs and execution seems to go nowhere. nothing happens after that.</p>
  
  <p>What am I missing here?</p>