How to customize bearer header keyword in asp.net core for JwtBearer and System.IdentityModel.Tokens.Jwt?
The implementation of the JwtBearer authentication handler lives inside of JwtBearerHandler
, where the Authorization
header is read and split using the format Bearer ...
. Here's what that looks like:
string authorization = Request.Headers["Authorization"]; // If no authorization header found, nothing to process further if (string.IsNullOrEmpty(authorization)) { return AuthenticateResult.NoResult(); } if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) { token = authorization.Substring("Bearer ".Length).Trim(); } // If no token found, no further work possible if (string.IsNullOrEmpty(token)) { return AuthenticateResult.NoResult(); }
As the code above shows, this is hardcoded to use Bearer
. However, JwtBearerEvents
includes an OnMessageReceived
property that allows you to hook into the process for retrieving the JWT from the incoming request. If you provide an implementation for this event, you can use your own processing to extract the JWT however you would like to. Taking the implementation from above with a few changes, that event handler implementation would like something like this:
x.Events = new JwtBearerEvents
{
// ...
OnMessageReceived = context =>
{
string authorization = context.Request.Headers["Authorization"];
// If no authorization header found, nothing to process further
if (string.IsNullOrEmpty(authorization))
{
context.NoResult();
return Task.CompletedTask;
}
if (authorization.StartsWith("Token ", StringComparison.OrdinalIgnoreCase))
{
context.Token = authorization.Substring("Token ".Length).Trim();
}
// If no token found, no further work possible
if (string.IsNullOrEmpty(context.Token))
{
context.NoResult();
return Task.CompletedTask;
}
return Task.CompletedTask;
}
};