isValidCognitoToken - Performance impacted by not caching JWKS files
Before opening, please confirm:
- [X] I have searched for duplicate or closed issues and discussions.
- [X] I have read the guide for submitting bug reports.
- [X] I have done my best to include a minimal, self-contained set of instructions for consistently reproducing the issue.
JavaScript Framework
Next.js
Amplify APIs
Authentication
Amplify Version
@aws-amplify/adapter-nextjs: 1.2.1
Introduced by this commit: https://github.com/aws-amplify/amplify-js/commit/125c690236da6cbc67117dc1d894d353bc436d54
Amplify Categories
auth
Backend
None
Environment information
# Put output below this line
Describe the bug
The changes to validate the cognito tokens as part of fetchSession in packages/adapter-nextjs/src/utils/isValidCognitoToken.ts call CognitoJwtVerifier.create on every request (@see https://github.com/aws-amplify/amplify-js/commit/125c690236da6cbc67117dc1d894d353bc436d54#r145308092).
CognitoJwtVerifier creates a cache of the downloaded jwks files. Creating a new instance on every request negates the cache. Which means many calls to get the JWKS file, slowing down each requets.
Prior to this release we were manually verifying the token in our NextJS middleware, since updating noticed a massive increase in the requests to the JWKS file, and a slow down in our test suites.
Expected behavior
That there would be some caching of JWKS file requests, i.e. 1 per application startup
Reproduction steps
In an application that is calling fetchAuthSession.
Something like ...
return await runWithAmplifyServerContext({
nextServerContext: { request, response },
operation: async (contextSpec) => {
try {
await fetchAuthSession(contextSpec)
const session = await fetchAuthSession(contextSpec);
if (session) {
return true;
}
return false;
} catch (error) {
console.log(error);
return false;
}
},
});
Will make 2 requests to the JWKS file, and will take 100ms at least longer than if its only there once.
Code Snippet
// Put your code below this line.
Log output
// Put your logs below this line
aws-exports.js
No response
Manual configuration
No response
Additional configuration
No response
Mobile Device
No response
Mobile Operating System
No response
Mobile Browser
No response
Mobile Browser Version
No response
Additional information and screenshots
No response
Thanks for pointing this out @smozely, we are currently exploring a better approach to perform the token validation on the server side, and we will include this performance improvement in the consideration.
Hi @smozely sorry about losing track of this issue. We have released an performance improvement regarding this issue since [email protected] and @aws-amplify@adapter-nextjs@@1.3.1 (released on 2024-12-09). I'm closing this issue, please feel free to reach out if anything. Thanks again for your suggestions.
Thanks, I noticed that had been released and we have been using the updated version