I am prototyping the use IdentityServer4 to secure several services, with the caveat that those services will likely not be migrated (in the forseeable future) to use the OWIN middleware idiom of ASP.NET Core. Consequently, I can not leverage the many middleware helpers that automate the validation of a JWT by simply providing the well-known JWKS endpoint of IdentityServer, among other things.
It would be nice if I could reconstruct this behavior, and I'd like to leverage Microsoft's
ClaimsPrincipal ValidateJwt(string token, IdentityModel.Client.DiscoveryResponse discovery)
JwtSecurityToken jwt = new JwtSecurityToken(token);
TokenValidationParameters validationParameters = new TokenValidationParameters
ValidateAudience = true,
ValidateIssuer = true,
RequireSignedTokens = true,
ValidIssuer = "expected-issuer",
ValidAudience = "expected-audience",
IssuerSigningKeys = discovery.KeySet.Keys /* not quite */
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
return handler.ValidateToken(jwt, validationParameters, out validatedToken);
Check this sample:
It manually retrieves the key from the JWK and populates the validation parameters.