Skip to content

Commit

Permalink
Reload jwk set if kid not found
Browse files Browse the repository at this point in the history
  • Loading branch information
anakinj committed Dec 1, 2018
1 parent b9a2a11 commit c589499
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
16 changes: 15 additions & 1 deletion lib/jwt/decode.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,21 @@ def find_key(&keyfinder)

def find_from_jwk(jwks)
raise JWT::DecodeError, 'No key id (kid) found from token headers' unless header['kid']
jwk = jwks[:keys].find { |key| key[:kid] == header['kid'] }

lazy = jwks.respond_to?(:call)
keys = if lazy
jwks.call({})
else
jwks
end

jwk = keys[:keys].find { |key| key[:kid] == header['kid'] }

if lazy && !jwk
keys = jwks.call(invalidate: true)
jwk = keys[:keys].find { |key| key[:kid] == header['kid'] }
end

raise JWT::DecodeError, "Could not find public key for kid #{header['kid']}" unless jwk

JWT::JWK.import(jwk).keypair
Expand Down
17 changes: 16 additions & 1 deletion spec/decode_with_jwk_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
end
end

context 'when jwk keys are given' do
context 'when jwk keys are given as an array' do
context 'and kid is in the set' do
it 'is able to decode the token' do
payload, _header = described_class.decode(signed_token, nil, true, { algorithms: ['RS512'], jwks: public_jwks})
Expand Down Expand Up @@ -51,5 +51,20 @@
end
end
end

context 'when jwk keys are loaded using a proc/lambda' do
it 'decodes the token' do
payload, _header = described_class.decode(signed_token, nil, true, { algorithms: ['RS512'], jwks: lambda { |_opts| public_jwks }})
expect(payload).to eq(token_payload)
end
end

context 'when jwk keys are rotated' do
it 'decodes the token' do
key_loader = ->(options){ options[:invalidate] ? public_jwks : { keys: [] } }
payload, _header = described_class.decode(signed_token, nil, true, { algorithms: ['RS512'], jwks: key_loader})
expect(payload).to eq(token_payload)
end
end
end
end

0 comments on commit c589499

Please sign in to comment.