I am using WSO2 as my Identity Provider (IDP). It is putting the JWT in an header called "X-JWT-Assertion".
To feed this into the ASP.NET Core system, I added an OnMessageReceived event. This allows me to set the token to the value supplied in the header.
Here is the code that I have to do that (the key part is the last 3 lines of non-bracket code):
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie()
.AddJwtBearer(async options =>
{
options.TokenValidationParameters =
await wso2Actions.JwtOperations.GetTokenValidationParameters();
options.Events = new JwtBearerEvents()
{
// WSO2 sends the JWT in a different field than what is expected.
// This allows us to feed it in.
OnMessageReceived = context =>
{
context.Token = context.HttpContext.Request.Headers["X-JWT-Assertion"];
return Task.CompletedTask;
}
}
};
This all works perfectly except for the very first call after the service starts up. To be clear, every call, except for the first one works exactly as I want it to. (It puts the token in and updates the User object like I need.)
But for the first call, the OnMessageReceived is not hit. And the User object in my controller is not setup.
I checked HttpContext for that first call, and the "X-JWT-Assertion" header is in the Request.Headers list (with the JWT in it). But, for some reason, the OnMessageReceived event is not called for it.
How can I get OnMessageReceived to be called for the first invocation of a service operation for my service?
IMPORTANT NOTE: I figured out that the issue was async await in AddJwtBearer. (See my answer below.) That is what I really wanted out of this question.
However, since a bounty cannot be cancled, I will still award the bounty to anyone who can show a way to use AddJwtBearer with async await where it is awaiting an actual HttpClient call. Or show documentation of why async await is not supposed to be used with AddJwtBearer.