简体   繁体   中英

Trying to inject Authorization header using OWIN before authorization happens in ASP.net Web API

I'm using Owin for JWT authentication. All my requests come back as "401 Unauthorized".

I'm trying to intercept all requests to my web application so that I can retrieve a JWT token from a cookie.

Adding an Authorization Header with a Bearer token works and authorizes correctly.

The middleware gets hit on every request, grabs the cookie successfully, and updates the header successfully (in the context object).


        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);
        }


    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);
        }
    }

The ideal workflow is:

  1. Cookie (which holds the JWT) gets sent with the request

  2. Owin middleware intercepts this, takes the token out of the cookie and appends an Authorization header

  3. API call gets authenticated with an Authorization Bearer header.

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.

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.

I believe I have solved this. It was a two part problem.

In my Startup.cs, this piece of code

                TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSecret)),

                    ValidateLifetime = true
                }
            });

was leading Owin to always return the token as unauthorized. I must have changed this at some point and never rechecked. I made it check for ValidIssuer and ValidAudience and we are good again.

The other piece of the puzzle was to have my custom middlewear load first, before the JWT authentication.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM