Class: AuthAction::JwtVerifier

Inherits:
Object
  • Object
show all
Defined in:
lib/authaction/jwt_verifier.rb

Overview

Core JWT verifier.

Fetches the JWKS from https://<domain>/.well-known/jwks.json, caches the key set in memory (TTL: 5 minutes), and busts the cache when an unknown kid is seen (key rotation).

Examples:

verifier = AuthAction::JwtVerifier.new(
  domain:   "myapp.eu.authaction.com",
  audience: "https://api.myapp.com"
)
payload = verifier.verify_token(token)

Constant Summary collapse

CACHE_TTL =

seconds

300

Instance Method Summary collapse

Constructor Details

#initialize(domain:, audience:) ⇒ JwtVerifier

Returns a new instance of JwtVerifier.



22
23
24
25
26
27
28
29
# File 'lib/authaction/jwt_verifier.rb', line 22

def initialize(domain:, audience:)
  @issuer   = "https://#{domain}"
  @jwks_uri = "https://#{domain}/.well-known/jwks.json"
  @audience = audience
  @mutex    = Mutex.new
  @cache    = nil
  @cached_at = nil
end

Instance Method Details

#verify_request(authorization_header) ⇒ Hash?

Extract and verify the Bearer token from an Authorization header value.

Returns nil when the header is absent or not a Bearer scheme. Never raises — returns nil on invalid or expired tokens.

Parameters:

  • authorization_header (String, nil)

Returns:

  • (Hash, nil)

    decoded claims or nil



61
62
63
64
65
66
67
68
# File 'lib/authaction/jwt_verifier.rb', line 61

def verify_request(authorization_header)
  return nil unless authorization_header&.start_with?("Bearer ")

  token = authorization_header[7..].strip
  verify_token(token)
rescue TokenExpiredError, TokenInvalidError
  nil
end

#verify_token(token) ⇒ Hash

Verify a raw JWT string and return the decoded payload hash.

Parameters:

  • token (String)

    raw JWT

Returns:

  • (Hash)

    decoded claims

Raises:



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/authaction/jwt_verifier.rb', line 37

def verify_token(token)
  payload, _header = JWT.decode(
    token, nil, true,
    algorithms: ["RS256"],
    iss:        @issuer,
    verify_iss: true,
    aud:        @audience,
    verify_aud: true,
    jwks:       method(:jwks_loader)
  )
  payload
rescue JWT::ExpiredSignature
  raise TokenExpiredError, "Token has expired"
rescue JWT::DecodeError => e
  raise TokenInvalidError, e.message
end