Last active
March 23, 2021 18:56
-
-
Save choncou/18161b215fcc8ad2a44e256079f22ef3 to your computer and use it in GitHub Desktop.
Verify JWTs with JWKS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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