I was having some trouble figuring out how to go about validating a JWT given to the client by AWS Cognito inside my .NET Core Web API.
Not only could I not figure out what the variables for Microsoft.IdentityModel.Tokens.TokenValidationParameters
were supposed to be, but once I finally did, I didn't know how to retrieve the JWT key set from https://cognito-idp.{region}.amazonaws.com/{pool ID}/.well-known/jwks.json
Finally, though a lot of random Googling and trial and error, I found a (seemingly-not-very-efficient solution) solution. However, I spent way too much time doing it. Citing that, plus the fact that AWS documentation on the subject is severely lacking, I decided to post this Q&A to help others find this solution more easily in the future.
If there's a better way to do this, somebody please tell me because I have yet to find a way to do this besides my answer listed below.
The answer lies primarily in correctly defining the
TokenValidationParameters.IssuerSigningKeyResolver
(parameters, etc. seen here: https://learn.microsoft.com/en-us/dotnet/api/microsoft.identitymodel.tokens.issuersigningkeyresolver?view=azure-dotnet).This is what tells .NET Core what to verify the JWT sent against. One must also tell it where to find the list of keys. One cannot necessarily hard-code the key set, as it is often rotated by AWS.
One way to do it would be to fetch and serialize the list from the URL inside the
IssuerSigningKeyResolver
method. The whole.AddJwtBearer()
might look something like this:Startup.cs ConfigureServices() method:
If you use a JS library such as AWS Amplify, you can see parameters such as the
ValidIssuer
andValidAudience
in your browser's console by observing the result ofAuth.currentSession()
A REST fetch request from a JS client to a .NET Core Web API utilizing the JWT Authentication achieved above as well as using the
[Authorize]
tag on your controller might look something like this:JS Client using @aws-amplify/auth node package: