Class: Stytch::JWKSCache
- Inherits:
-
Object
- Object
- Stytch::JWKSCache
- Includes:
- RequestHelper
- Defined in:
- lib/stytch/jwks_cache.rb
Overview
JWKSCache handles caching and refreshing of JSON Web Key Sets (JWKS) for JWT signature verification. It can be initialized with pre-cached keys or will fetch them on-demand from the Stytch API.
Constant Summary collapse
- CACHE_EXPIRY_SECONDS =
5 minutes
300
Instance Method Summary collapse
-
#get_jwks(project_id:) ⇒ Object
Fetches JWKS from the Stytch API using the appropriate endpoint.
-
#initialize(connection, project_id, jwks = nil, is_b2b_client: false) ⇒ JWKSCache
constructor
A new instance of JWKSCache.
-
#loader ⇒ Object
Returns a lambda suitable for use with JWT.decode.
Methods included from RequestHelper
#delete_request, #get_request, #post_request, #put_request, #request_with_query_params
Constructor Details
#initialize(connection, project_id, jwks = nil, is_b2b_client: false) ⇒ JWKSCache
Returns a new instance of JWKSCache.
14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/stytch/jwks_cache.rb', line 14 def initialize(connection, project_id, jwks = nil, is_b2b_client: false) @connection = connection @project_id = project_id @is_b2b_client = is_b2b_client @cache_last_update = 0 # If jwks are provided during initialization, use them directly return unless jwks @cached_keys = { keys: jwks } @cache_last_update = Time.now.to_i end |
Instance Method Details
#get_jwks(project_id:) ⇒ Object
Fetches JWKS from the Stytch API using the appropriate endpoint
43 44 45 46 47 48 49 50 51 |
# File 'lib/stytch/jwks_cache.rb', line 43 def get_jwks(project_id:) endpoint = if @is_b2b_client "/v1/b2b/sessions/jwks/#{project_id}" else "/v1/sessions/jwks/#{project_id}" end get_request(endpoint, {}) end |
#loader ⇒ Object
Returns a lambda suitable for use with JWT.decode
28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/stytch/jwks_cache.rb', line 28 def loader lambda do || @cached_keys = nil if [:invalidate] && @cache_last_update < Time.now.to_i - CACHE_EXPIRY_SECONDS @cached_keys ||= begin @cache_last_update = Time.now.to_i keys = [] get_jwks(project_id: @project_id)['keys'].each do |r| keys << r end { keys: keys } end end end |