Skip to content

Instantly share code, notes, and snippets.

@choncou

choncou/verify_jwt.rb

Last active Mar 23, 2021
Embed
What would you like to do?
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