12

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.

Nate Barbettini
  • 51,256
  • 26
  • 134
  • 147
Lutando
  • 4,909
  • 23
  • 42

1 Answers1

11

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.

Nate Barbettini
  • 51,256
  • 26
  • 134
  • 147
  • 1
    Thanks a lot for this. I did scan the source but didnt put two and two together wrt the line of code that you linked. Works like a charm. For anyone interested i'm having to add the Bearer token in the query string because we are using SignalR (we don't want to use cookies) and want to pull the token from the query string instead. – Lutando Jan 31 '17 at 18:55
  • @Lutando Glad to help! – Nate Barbettini Jan 31 '17 at 19:03