# Feedback on Caching JWKS for JWT Verification in Ruby

**URL:** <https://community.auth0.com/t/feedback-on-caching-jwks-for-jwt-verification-in-ruby/138885>\
**Category:** Get Help\
**Tags:** apis, application\
**Created:** [July 15, 2024, 5:39am UTC](https://community.auth0.com/t/feedback-on-caching-jwks-for-jwt-verification-in-ruby/138885 "2024-07-15T05:39:19Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![raphael.egeley](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/raphael.egeley/32/58591_2.png) [@raphael.egeley](https://community.auth0.com/u/raphael.egeley)\
**Post date:** [July 15, 2024, 5:39am UTC](https://community.auth0.com/t/feedback-on-caching-jwks-for-jwt-verification-in-ruby/138885/1 "2024-07-15T05:39:19Z")

</div>

Hello Auth0 Community,

I have implemented JWT verification in my application by following the Auth0 documentation. After further reading on [how to locate JSON Web Key Sets](https://auth0.com/docs/secure/tokens/json-web-tokens/locate-json-web-key-sets), I decided to enhance the efficiency of the process by implementing caching. This way, I avoid performing an HTTP request to Auth0 for each token verification.

Here’s the code snippet I’m using for caching the JWKS:

```auto
# frozen_string_literal: true

require "net/http"
require "uri"

class JsonWebToken
  TOKEN_ISSUER = ENV.fetch("AUTH0_TOKEN_ISSUER").chomp("/").concat("/")
  AUDIENCE = ENV.fetch("AUTH0_AUDIENCE")
  JWKS_CACHE_EXPIRE_IN = 2.hours

  def self.verify(token, retrying: false)
    JWT.decode(
      token,
      nil,
      true, # Verify the signature of this token
      algorithms: "RS256",
      iss: TOKEN_ISSUER,
      verify_iss: true,
      aud: AUDIENCE,
      verify_aud: true
    ) do |header|
      jwks_hash[header["kid"]]
    end
  rescue JWT::DecodeError => e
    raise if retrying

    Rails.cache.delete("jwks_keys")
    verify(token, retrying: true)
  end

  def self.jwks_hash(force_update = false)
    Rails.cache.fetch("jwks_keys", force: force_update, expires_in: JWKS_CACHE_EXPIRE_IN) do
      jwks_raw = Net::HTTP.get URI("#{TOKEN_ISSUER}.well-known/jwks.json")
      jwks_keys = Array(JSON.parse(jwks_raw)["keys"])
      jwks_keys.map do |key|
        [
          key["kid"],
          OpenSSL::X509::Certificate.new(
            Base64.decode64(key["x5c"].first)
          ).public_key
        ]
      end.to_h
    end
  end
end

```

I would greatly appreciate any feedback on this implementation:

1. Is this implementation correct and secure according to best practices?
2. What is the recommended expiration time for caching the JWKS?
3. Are there any other recommendations or best practices I might have missed?

Thank you for your time and assistance!

---

<div class="post-metadata">

**Author:** ![ty.frith](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/ty.frith/32/58484_2.png) [@ty.frith](https://community.auth0.com/u/ty.frith)\
**Post date:** [July 15, 2024, 5:53pm UTC](https://community.auth0.com/t/feedback-on-caching-jwks-for-jwt-verification-in-ruby/138885/3 "2024-07-15T17:53:20Z")

</div>

Hey @raphael.egeley welcome to the community!

> [@raphael.egeley](#):
>
> After further reading on [how to locate JSON Web Key Sets](https://auth0.com/docs/secure/tokens/json-web-tokens/locate-json-web-key-sets), I decided to enhance the efficiency of the process by implementing caching. This way, I avoid performing an HTTP request to Auth0 for each token verification.

Great Idea! Overall, I think your approach is good - There isn’t a recommended time to cache tokens. The following post expands on caching JWKs and is still useful despite being a few years old.

> [@Caching JWKS signing key](https://community.auth0.com/t/caching-jwks-signing-key/17654/2):
>
> Hi @benji. (This response was updated on April 2021 to reflect signing keys rotation and updated guidance on caching). Auth0 nows support signing key rotation initiated by tenant admins (see [Signing Keys](https://auth0.com/docs/tokens/manage-signing-keys) for details). A tenant’s JWKS resource will have the current key and the “next” key, so applications that prepare in advance for a key rotation. The JWKS resource will return the same set of keys most of the time. Applications should cache these resources, but they also need to be prepared to…

---

<div class="post-metadata">

**Author:** ![system](https://global.discourse-cdn.com/auth0/original/3X/b/5/b560f266932fcce5d57f09a6595bd50518cae3f3.jpeg) [@system](https://community.auth0.com/u/system)\
**Post date:** [July 29, 2024, 5:53pm UTC](https://community.auth0.com/t/feedback-on-caching-jwks-for-jwt-verification-in-ruby/138885/4 "2024-07-29T17:53:22Z")

</div>

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