Class: RackJwtVerifier::Verifier

Inherits:
Object
  • Object
show all
Defined in:
lib/rack_jwt_verifier/verifier.rb

Overview

This class handles the cryptographic heavy lifting: fetching and caching public keys from the SSO provider, and performing the actual JWT decoding and signature verification.

Defined Under Namespace

Classes: KeyFetchError

Constant Summary collapse

PUBLIC_KEY_CACHE_KEY =

The cache key used to store the public key PEM string

'rack_jwt_verifier:public_key'.freeze
CACHE_TTL_SECONDS =

The TTL for the cache (5 minutes, must match the default in InProcessCache)

300
DEFAULT_DECODE_OPTIONS =

Default options for JWT decoding to ensure strict security compliance

{
  algorithm: "RS256", # Must match your SSO provider's algorithm
  # THIS MUST BE TRUE: Ensures the 'exp' claim is checked during decoding
  verify_expiration: true,
  verify_not_before: true,
  leeway: 60, # Allow a 60-second clock skew for "exp" and "nbf" claims
  # 'iss' validation will be added later when we configure the Verifier.
  # verify_iss: true
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Verifier

Returns a new instance of Verifier.

Parameters:

  • options (Hash) (defaults to: {})

    Configuration options.

Options Hash (options):

  • :public_key_url (String)

    The URL to fetch the public key.

  • :cache_store (Object)

    Optional custom cache object (must respond to #read and #write).

  • :decode_options (Hash)

    Custom options for JWT.decode.



35
36
37
38
39
40
41
42
43
44
# File 'lib/rack_jwt_verifier/verifier.rb', line 35

def initialize(options = {})
  @public_key_url = options.fetch(:public_key_url)
  
  # Inject cache store, defaulting to the simple InProcessCache.
  # This allows users to pass in a Redis/Memcached client that responds to #read and #write.
  @cache = options.fetch(:cache_store, InProcessCache.new)
  
  # Merge default options over any user-provided options
  @decode_options = DEFAULT_DECODE_OPTIONS.merge(options.fetch(:decode_options, {}))
end

Instance Method Details

#verify(token) ⇒ Hash

Decodes and verifies the JWT.

Parameters:

  • token (String)

    The JWT string from the Authorization header.

Returns:

  • (Hash)

    The decoded payload (the user claims).

Raises:

  • (JWT::DecodeError)

    If the token is invalid, expired, or signature fails.



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/rack_jwt_verifier/verifier.rb', line 50

def verify(token)
  # 1. Fetch the key from cache or network
  key = fetch_public_key

  # 2. Perform the cryptographic verification and claim validation
  # The `true` is required to enable verification checks.
  payload, _header = JWT.decode(token, key, true, @decode_options)
  
  # For standard usage, we only need the payload hash
  payload
end