So we were upgrading to asp.net core, the old system where using a custom jwt validation. Since asp.net core Authentication comes with a built in AothenticationBuilder for Jwt we decided to use that one instead (seems reasonable right?)
One thing was that the old system where not using the Authorization header and where accepting with or without Bearer
first.
So we needed a way to look at the custom header for a token and forward it to asp.net Authentication. Of course there is a simple solution to this. Here it is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
services.AddAuthentication() .AddJwtBearer(options => { options.Events = new JwtBearerEvents { OnMessageReceived = ctx => { if (ctx.Request.Headers.ContainsKey("SpecialApiKey")) { var bearerToken = ctx.Request.Headers["SpecialApiKey"].ElementAt(0); var token = bearerToken.StartsWith("Bearer ") ? bearerToken.Substring(7) : bearerToken; ctx.Token = token; } return Task.CompletedTask; } }; }); |
We simply add a new callback to OnMessageReceived
in the Events
.
We look for a header with the name SpecialApiKey
then we see if it starts with Bearer and if so we strip that part out.
That’s all. Pretty smooth right?
Until next time, have a good one.