diff --git a/lib/jwt/encoded_token.rb b/lib/jwt/encoded_token.rb index d31d9b6a..0e76aec1 100644 --- a/lib/jwt/encoded_token.rb +++ b/lib/jwt/encoded_token.rb @@ -125,10 +125,8 @@ def verify_signature!(algorithm:, key: nil, key_finder: nil) key ||= key_finder.call(self) - if valid_signature?(algorithm: algorithm, key: key) - @signature_verified = true - return - end + return if valid_signature?(algorithm: algorithm, key: key) + raise JWT::VerificationError, 'Signature verification failed' end @@ -138,11 +136,13 @@ def verify_signature!(algorithm:, key: nil, key_finder: nil) # @param key [String, Array] the key(s) to use for verification. # @return [Boolean] true if the signature is valid, false otherwise. def valid_signature?(algorithm:, key:) - Array(JWA.resolve_and_sort(algorithms: algorithm, preferred_algorithm: header['alg'])).any? do |algo| + valid = Array(JWA.resolve_and_sort(algorithms: algorithm, preferred_algorithm: header['alg'])).any? do |algo| Array(key).any? do |one_key| algo.verify(data: signing_input, signature: signature, verification_key: one_key) end end + + valid.tap { |verified| @signature_verified = verified } end # Verifies the claims of the token. diff --git a/spec/jwt/encoded_token_spec.rb b/spec/jwt/encoded_token_spec.rb index fd48fa85..42008da5 100644 --- a/spec/jwt/encoded_token_spec.rb +++ b/spec/jwt/encoded_token_spec.rb @@ -51,12 +51,26 @@ end describe '#payload' do - context 'when token is verified' do + context 'when token is verified using #verify_signature!' do before { token.verify_signature!(algorithm: 'HS256', key: 'secret') } it { expect(token.payload).to eq(payload) } end + context 'when token is checked using #valid_signature?' do + before { token.valid_signature?(algorithm: 'HS256', key: 'secret') } + + it { expect(token.payload).to eq(payload) } + end + + context 'when token is verified using #valid_signature? but is not valid' do + before { token.valid_signature?(algorithm: 'HS256', key: 'wrong') } + + it 'raises an error' do + expect { token.payload }.to raise_error(JWT::DecodeError, 'Verify the token signature before accessing the payload') + end + end + context 'when token is not verified' do it 'raises an error' do expect { token.payload }.to raise_error(JWT::DecodeError, 'Verify the token signature before accessing the payload')