title: Authentication in WebApi with AllowAnonymous attribute
body: <p>I have implemented a JWT-based authentication by inheriting <code>DelegatingHandler</code> and adding the class as <code>configuration.MessageHandlers.Add(new MyDelegatingHandler())</code>.</p>
  
  <p>When implementing <code>DelegatingHandler</code>, I override <code>Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)</code>. The logic is simple there - I retrieve a token from <code>Authorization</code> header, check it's validity. If it is valid - I set <code>Thread.CurrentPrincipal</code> and <code>HttpContext.Current.User</code>, otherwise I return <code>new HttpResponseMessage(HttpStatusCode.Unauthorized)</code></p>
  
  <p>Basically it looks like this (very simplified):</p>
  
  <pre><code>public class TokenValidationHandler : DelegatingHandler
  {
      protected override Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
      {
          var token = GetTokenFromAuthorizeHeader(request);
          if (TokenIsValid(token)) {
             var principal = CreatePrincipal(token);
             Thread.CurrentPrincipal = principal;
             HttpContext.Current.User = principal;
             return base.SendAsync(request, cancellationToken);
          } else {
             // TODO: fix
             return Task&lt;HttpResponseMessage&gt;.Factory.StartNew(() =&gt; new HttpResponseMessage(HttpStatusCode.Unauthorized));
          }
      }
  }
  </code></pre>
  
  <p>Now this method is called even on WebApi method that has <code>[AllowAnonymous]</code> attribute with it. This is good because I want to set principal even if the method allows anonymous. But this logic fails if the supplied token in <code>Authorization</code> header is invalid. </p>
  
  <p>User sends a request to resource with <code>[AllowAnonymous]</code> and with an invalid token in <code>Authorization</code> header, which should come through because the resourse allows anonymous, but my code checks authorization, find out that the token is invalid and sends <code>HttpStatusCode.Unauthorized</code>.</p>
  
  <p>The fix would be to check where <code>// TODO: fix</code> is whether the resource the user is accessing allows anonymous or not, and only send <code>HttpStatusCode.Unauthorized</code> if it is not, but I can't figure out how to properly do this.</p>
  
  <p>How can I do this?</p>