Skip to content

Instantly share code, notes, and snippets.

@choncou
Last active March 23, 2021 18:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save choncou/18161b215fcc8ad2a44e256079f22ef3 to your computer and use it in GitHub Desktop.
Save choncou/18161b215fcc8ad2a44e256079f22ef3 to your computer and use it in GitHub Desktop.
Verify JWTs with JWKS
module Auth
module VerifyJwt
extend self
JWKS_CACHE_KEY = "auth/jwks-json".freeze
JWKS_URL = "https://#{Rails.configuration.auth0[:auth_domain]}/.well-known/jwks.json".freeze
def call(token)
JWT.decode(
token,
nil,
true, # Verify the signature of this token
algorithms: ["RS256"],
iss: "https://#{Rails.configuration.auth0[:auth_domain]}/",
verify_iss: true,
aud: Rails.configuration.auth0[:web_audience],
verify_aud: true,
jwks: jwk_loader,
)
end
private
def jwk_loader
->(options) do
jwks(force: options[:invalidate]) || {}
end
end
def fetch_jwks
response = HTTP.get(JWKS_URL)
if response.code == 200
JSON.parse(response.body.to_s)
end
end
def jwks(force: false)
Rails.cache.fetch(JWKS_CACHE_KEY, force: force, skip_nil: true) do
fetch_jwks
end&.deep_symbolize_keys
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment