title: Why does my authentication middleware pass a request to the authorization filter when no token is supplied?
body: <p>I have a .NET Core 1.1 Web API which uses JWT authentication middleware and a custom authorization filter.  They are defined like this:</p>
  
  <pre><code>services.AddSingleton&lt;IAuthorizationRequirement, MercuryEndpointAuthorizationHandler&gt;();
  services.AddSingleton&lt;IEndpointAuthorizeDictionary, EndpointRights&gt;();
  services.AddSingleton&lt;IAuthorizationHandler, MercuryEndpointAuthorizationHandler&gt;();
  
  services.AddAuthorization(options =&gt;
  {
      options.AddPolicy("AuthorizeMercuryEndpoint", policy =&gt;
      {
          policy.AddRequirements(services.BuildServiceProvider().GetService&lt;IAuthorizationRequirement&gt;());
      });
  });
  </code></pre>
  
  <p>and </p>
  
  <pre><code>app.UseJwtBearerAuthentication(new JwtBearerOptions
  {
      AutomaticAuthenticate = true,
      AutomaticChallenge = true,
      TokenValidationParameters = tokenValidationParameters,
      Events = new JwtBearerEvents()
      {
          OnMessageReceived = async (context) =&gt;
          {
              Debug.WriteLine("====&gt;  JWT Message received");
          },
          OnTokenValidated = async (context) =&gt;
          {
              Debug.WriteLine("====&gt;  JWT token validated");
              context.HttpContext.Items["JwtTokenIsValid"] = true;
          },
          OnAuthenticationFailed = async (context) =&gt;
          {
              Debug.WriteLine("====&gt;  JWT token failed auth");
              context.HttpContext.Items["JwtTokenIsValid"] = false;
              if ((AuthenticationType.IdServer &amp; authTypes) != 0)
                  context.SkipToNextMiddleware();
          }
      }
  });
  </code></pre>
  
  <p>When I call an endpoint protected with <code>[Authorize("AuthorizeMercuryEndpoint")]</code> and a valid JWT token, the call succeeds as expected, and I see the following debug written by the process:</p>
  
  <pre><code>====&gt;  JWT Message received
  ====&gt;  JWT token validated
  ====&gt;  Request authorized (when the auth filter succeeds)
  </code></pre>
  
  <p>However, if I do not pass a token, the JWT middleware appears to pass the request straight to the authorization filter without attempting authentication - neither <code>OnTokenValidated</code> nor <code>OnAuthenticationFailed</code> are called, and when authorization fails (because there is no authenticated identity) the pipeline is terminated.</p>
  
  <p>This is a problem because I want to pass the request to a second authentication middleware if the JWT token validation fails the initial authentication.</p>
  
  <p>Does anyone know what the recommended approach for this is?</p>