Class: JWT::JWK::KeyFinder

Inherits:
Object
  • Object
show all
Defined in:
lib/jwt/jwk/key_finder.rb

Overview

JSON Web Key keyfinder To find the key for a given kid

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ KeyFinder

Initializes a new KeyFinder instance.

Parameters:

  • options (Hash)

    the options to create a KeyFinder with

Options Hash (options):

  • :jwks (Proc, JWT::JWK::Set)

    the jwks or a loader proc

  • :allow_nil_kid (Boolean)

    whether to allow nil kid

  • :key_fields (Array)

    the fields to use for key matching, the order of the fields are used to determine the priority of the keys.



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/jwt/jwk/key_finder.rb', line 15

def initialize(options)
  @allow_nil_kid = options[:allow_nil_kid]
  jwks_or_loader = options[:jwks]

  @jwks_loader = if jwks_or_loader.respond_to?(:call)
                   jwks_or_loader
                 else
                   ->(_options) { jwks_or_loader }
                 end

  @key_fields = options[:key_fields] || %i[kid]
end

Instance Method Details

#call(token) ⇒ Object

Returns the key for the given token

Parameters:

Raises:



43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/jwt/jwk/key_finder.rb', line 43

def call(token)
  @key_fields.each do |key_field|
    field_value = token.header[key_field.to_s]

    return key_for(field_value, key_field) if field_value
  end

  raise ::JWT::DecodeError, 'No key id (kid) or x5t found from token headers' unless @allow_nil_kid

  kid = token.header['kid']
  key_for(kid)
end

#key_for(kid, key_field = :kid) ⇒ Object

Returns the verification key for the given kid

Parameters:

  • kid (String)

    the key id

Raises:



30
31
32
33
34
35
36
37
38
39
# File 'lib/jwt/jwk/key_finder.rb', line 30

def key_for(kid, key_field = :kid)
  raise ::JWT::DecodeError, "Invalid type for #{key_field} header parameter" unless kid.nil? || kid.is_a?(String)

  jwk = resolve_key(kid, key_field)

  raise ::JWT::DecodeError, 'No keys found in jwks' unless @jwks.any?
  raise ::JWT::DecodeError, "Could not find public key for kid #{kid}" unless jwk

  jwk.verify_key
end