We have been successfully using IdentityServer4.AccessTokenValidation 2.1.0 with our .NET Core 2.0 web api. New requirement was recently added to store the validated access token as a claim on the current ClaimsIdentity so API1 can call API2 under the same jwt user context. Added the following code to the identity server options to handle this but doesn't seem to work as the ClaimsIdentity does not have a "access_token" claim. Please let me know if I wired this up incorrectly in API code:
// Register Authentication
services.AddAuthentication("Bearer")
//From https://github.com/IdentityServer/IdentityServer4.AccessTokenValidation (nuget)
.AddIdentityServerAuthentication(options =>
{
options.Authority = Configuration["IdentityServer:Authority"];
options.RequireHttpsMetadata = false;
options.ApiName = "API1";
//We need to be able to retreive the authenticated token so we can use it to call api2
//https://www.jerriepelser.com/blog/aspnetcore-jwt-saving-bearer-token-as-claim/
options.Events = new JwtBearerEvents()
{
OnTokenValidated = tvContext =>
{
Console.WriteLine("*** OnTokenValidated callback.");
// Add the access_token as a claim
var accessToken = tvContext.SecurityToken as JwtSecurityToken;
if (accessToken != null)
{
ClaimsIdentity identity = tvContext.Principal.Identity as ClaimsIdentity;
if (identity != null)
{
identity.AddClaim(new Claim("access_token", accessToken.RawData));
}
}
return Task.CompletedTask;
}
};
});
Think we may have figured this out (at least in IdentityServer4.AccessTokenValidation 2.1.0).
Looks like you have to set options.JwtBearerEvents rather than options.Events...
options.JwtBearerEvents = new JwtBearerEvents()
I came across this issue a couple of times but my OnTokenValidated method was never called. My solution was not use JwtBearerEvents but OAuth2IntrospectionEvents because I use token introspection. Took me a couple of hours to figure this out so thought to leave my solution here for someone else.
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Most helpful comment
Think we may have figured this out (at least in IdentityServer4.AccessTokenValidation 2.1.0).
Looks like you have to set options.JwtBearerEvents rather than options.Events...