How do I properly cache the JWKS?

I’m developing an API in PHP and have some concerns regarding the caching of the JWKS keys.

To verify the JWT access tokens I have implemented a middleware that extracts the token from the request Authorization header and then verifies it using the the helpers in the Auth0 PHP SDK.

When I first implemented it, I simply used the JWKFetcher from the SDK with no concerns about caching (thinking it was handled by the SDK somehow). This quickly broke down when I tested it, since the middleware runs for each request and with enough requests, the Auth0 rate limit kicks in (well, something caused the verification to start failing during each burst of requests).

I then added a ChainAdapter from the Symfony cache library (“symfony/cache”), which used three levels of caching (in-memory, local filesystem and lastly the DB). This works quite well since the library offers stampede protection and locking, and as far as I understand it, it makes sure only one request will go ahead and download the JWK if the cached keys expired while any other requests wait for the cache to be recomputed.

The solution still doesn’t feel quite right to me since I have a nagging feeling it may cause other issues related to keeping several requests on hold (other than the API clients just waiting a little longer every once in a while), but I can’t say for sure.

Long story short: Is there a recommended way to handle downloading and caching of the JWK keys on a per-request basis? Is it even a good idea to do this on a per-request basis? Or should I just give up and store the JWK keys locally on the server?

Hi @marcusb
As long as your caching is respecting the kid then I think it should be okay.


1 Like

Yeah, I guess I’m just a little paranoid.
Thanks for the help!

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.