Class: JwtAuthCognito::JwksService

Inherits:
Object
  • Object
show all
Defined in:
lib/jwt_auth_cognito/jwks_service.rb

Instance Method Summary collapse

Constructor Details

#initialize(config = JwtAuthCognito.configuration) ⇒ JwksService

Returns a new instance of JwksService.



11
12
13
14
15
# File 'lib/jwt_auth_cognito/jwks_service.rb', line 11

def initialize(config = JwtAuthCognito.configuration)
  @config = config
  @cache = {}
  @cache_timestamps = {}
end

Instance Method Details

#validate_token_with_jwks(token) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/jwt_auth_cognito/jwks_service.rb', line 17

def validate_token_with_jwks(token)
  @config.validate!

  header = JWT.decode(token, nil, false).last
  kid = header['kid']

  raise ValidationError, 'Token missing key ID (kid)' unless kid

  public_key = get_public_key(kid)
  # First decode to check token type before audience validation
  payload_preview = JWT.decode(token, nil, false).first

  # Only verify audience for ID tokens, not access tokens
  # Access tokens from Cognito might not have 'aud' claim
  should_verify_aud = @config.cognito_client_id && payload_preview['token_use'] == 'id'

  decoded_token = JWT.decode(
    token,
    public_key,
    true,
    {
      algorithm: 'RS256',
      iss: @config.cognito_issuer,
      verify_iss: true,
      aud: should_verify_aud ? @config.cognito_client_id : nil,
      verify_aud: should_verify_aud
    }
  )

  payload = decoded_token.first
  validate_token_claims(payload)

  {
    valid: true,
    payload: payload,
    sub: payload['sub'],
    username: payload['cognito:username'] || payload['username'],
    token_use: payload['token_use']
  }
rescue JWT::DecodeError => e
  { valid: false, error: "JWT decode error: #{e.message}" }
rescue ValidationError => e
  { valid: false, error: e.message }
rescue StandardError => e
  { valid: false, error: "Validation error: #{e.message}" }
end