Search code examples
.netasp.net-corejwtasp.net-authorizationasp.net-core-middleware

Custom token location for JwtBearerMiddleware


We have a calling client requesting to our system that does not place the Bearer token in the standard place ('Authorization' header) I would like to create a custom handler that looks for the JWT in the correct place. Besides forking the JwtBearerMiddleware implementation is there any cleaner way I can just tell the middleware what handler to use?

Easier option would be to just rewrite the request by injecting the JWT into the correct place (the request header) in the request pipeline just before the JWT middleware runs. But this seems a bit hacky.


Solution

  • There's actually a built-in way to do this, without having to fork the code or try to provide your own handler. All you have to do is hook some code into the OnMessageReceived event:

    app.UseJwtBearerAuthentication(new JwtBearerOptions()
    {
        Events = new JwtBearerEvents()
        {
            OnMessageReceived = context =>
            {
                // Get the token from some other location
                // This can also await, if necessary
                var token = context.Request.Headers["MyAuthHeader"];
    
                // Set the Token property on the context to pass the token back up to the middleware
                context.Token = token;
    
                return Task.FromResult(true);
            }
        }
    });
    

    If you take a look at the source, the Token property is checked after the event handler is executed. If it's null, then the handler goes on with the default check for the Authorization header.