title: ASP.NET Core Middleware executes before authentication
body: <p>As part of the login flow, I need to check that a user has access to the application I'm writing. I do this by querying a legacy db with the user id. Afterwards, I want to add the legacy id to the request so I don't have to look it up each time. So I build a policy that retrieves the legacy id of the logged in user and adds it to the request. Then I wrote a <code>LoggingMiddleware</code> to add that legacy id as a log property.</p>
  
  <p>Both work nicely, but are executed in the wrong order. First the middleware is executed and then the authentication policy. So I'm constantly logging 'Anonymous' instead of the id I want to log. My <code>Startup</code> class has the correct order (I think), so I don't understand why it won't work correctly.</p>
  
  <p>Startup.cs:</p>
  
  <pre><code>    public virtual void ConfigureServices(IServiceCollection services)
      {
        var authenticationSettings = Configuration.GetSection(ConfigurationConstants.JwtSectionName).Get&lt;AuthenticationSettings&gt;();
        services
          .AddAuthorization(options =&gt;
            options.AddPolicy(SecurityConstants.PolicyName,
              new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build()))
          .AddScoped&lt;ISecurityQueries, SecurityQueries&gt;()
          .AddScoped&lt;IAuthorizationHandler, VerifyIdPolicy&gt;()
          .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
          .AddJwtBearer(options =&gt;
          {
            options.Authority = authenticationSettings.Authority;
            options.TokenValidationParameters = new TokenValidationParameters
            {
              ValidateAudience = false,
              ValidateLifetime = true,
              ValidateIssuer = true,
              ValidIssuers = authenticationSettings.Issuers.Split(';')
            };
          });
  
        services
          .ConfigureMvc&lt;ContractDomainException&gt;(Configuration)
          .ConfigureRefitClient&lt;IAppConfigApi&gt;(Configuration, DataContextTypes.AppConfig)
          .ConfigureServices()
          .ConfigureSwagger("Contract HTTP API")
          .ConfigureValidation(new Dictionary&lt;string, string&gt; {{Assembly.GetExecutingAssembly().FullName, DataContextTypes.Contract}});
      }
  
      public virtual void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
      {
        app
          .UseAuthentication()
          .UseCors()
          .UseMiddleware&lt;LoggingMiddlewareTest&gt;()
          .UseResponseCompression()
          .UseMvc();
      }
  </code></pre>
  
  <p>Controller.cs:</p>
  
  <pre><code>  [ApiController]
    [ApiVersion("1.0")]
    [Authorize(Policy = SecurityConstants.PolicyName)]
    public class ContractController : ControllerBase
  </code></pre>