title: Trying to inject Authorization header using OWIN before authorization happens in ASP.net Web API
body: <p>I'm using Owin for JWT authentication. All my requests come back as "401 Unauthorized".</p>
  
  <p>I'm trying to intercept all requests to my web application so that I can retrieve a JWT token from a cookie.</p>
  
  <p>Adding an Authorization Header with a Bearer token works and authorizes correctly.</p>
  
  <p>The middleware gets hit on every request, grabs the cookie successfully, and updates the header successfully (in the context object). </p>
  
  <pre class="lang-cs prettyprint-override"><code>
          public void Configuration(IAppBuilder app)
          {
              app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
              {
                  TokenValidationParameters = new TokenValidationParameters
                  {
                      IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSecret)),
  
                      ValidateLifetime = true
                  }
              });
  
              app.Use(typeof(JWTMiddleware));
  
              var config = new HttpConfiguration();
              WebApiConfig.Register(config);
  
              app.UseWebApi(config);
          }
  
  </code></pre>
  
  <pre class="lang-cs prettyprint-override"><code>
      public class JWTMiddleware: OwinMiddleware
      {
          public JWTMiddleware(OwinMiddleware next): base(next)
          {
          }
  
          public override async Task Invoke(IOwinContext context)
          {
              var name = "auth";
              var cookie = context.Request.Cookies[name];
              if (cookie != null)
              {
                  if (string.IsNullOrEmpty(context.Request.Headers.Get("Authorization")))
                  {
                      context.Request.Headers.Append("Authorization", "Bearer " + cookie);
                  }
              }
              await Next.Invoke(context);
          }
      }
  
  </code></pre>
  
  <p>The ideal workflow is:</p>
  
  <ol>
  <li><p>Cookie (which holds the JWT) gets sent with the request</p></li>
  <li><p>Owin middleware intercepts this, takes the token out of the cookie and appends an Authorization header</p></li>
  <li><p>API call gets authenticated with an Authorization Bearer header.</p></li>
  </ol>
  
  <p>If anyone is curious as to why I'm doing this....this is so my website can use http only cookies to store the token, and then from devices where a Bearer token is necessary I can just send that instead.</p>
  
  <p>Instead, I just always get 401 unauthorized. I suspect that its trying to authenticate the token before it gets intercepted by Owin? I'm not positive.</p>