Skip to content

Commit 3e13875

Browse files
committed
Count verifications done with #valid_signature?
1 parent 95dc43f commit 3e13875

File tree

2 files changed

+20
-6
lines changed

2 files changed

+20
-6
lines changed

lib/jwt/encoded_token.rb

+5-5
Original file line numberDiff line numberDiff line change
@@ -125,10 +125,8 @@ def verify_signature!(algorithm:, key: nil, key_finder: nil)
125125

126126
key ||= key_finder.call(self)
127127

128-
if valid_signature?(algorithm: algorithm, key: key)
129-
@signature_verified = true
130-
return
131-
end
128+
return if valid_signature?(algorithm: algorithm, key: key)
129+
132130
raise JWT::VerificationError, 'Signature verification failed'
133131
end
134132

@@ -138,11 +136,13 @@ def verify_signature!(algorithm:, key: nil, key_finder: nil)
138136
# @param key [String, Array<String>] the key(s) to use for verification.
139137
# @return [Boolean] true if the signature is valid, false otherwise.
140138
def valid_signature?(algorithm:, key:)
141-
Array(JWA.resolve_and_sort(algorithms: algorithm, preferred_algorithm: header['alg'])).any? do |algo|
139+
valid = Array(JWA.resolve_and_sort(algorithms: algorithm, preferred_algorithm: header['alg'])).any? do |algo|
142140
Array(key).any? do |one_key|
143141
algo.verify(data: signing_input, signature: signature, verification_key: one_key)
144142
end
145143
end
144+
145+
valid.tap { |verified| @signature_verified = verified }
146146
end
147147

148148
# Verifies the claims of the token.

spec/jwt/encoded_token_spec.rb

+15-1
Original file line numberDiff line numberDiff line change
@@ -51,12 +51,26 @@
5151
end
5252

5353
describe '#payload' do
54-
context 'when token is verified' do
54+
context 'when token is verified using #verify_signature!' do
5555
before { token.verify_signature!(algorithm: 'HS256', key: 'secret') }
5656

5757
it { expect(token.payload).to eq(payload) }
5858
end
5959

60+
context 'when token is checked using #valid_signature?' do
61+
before { token.valid_signature?(algorithm: 'HS256', key: 'secret') }
62+
63+
it { expect(token.payload).to eq(payload) }
64+
end
65+
66+
context 'when token is verified using #valid_signature? but is not valid' do
67+
before { token.valid_signature?(algorithm: 'HS256', key: 'wrong') }
68+
69+
it 'raises an error' do
70+
expect { token.payload }.to raise_error(JWT::DecodeError, 'Verify the token signature before accessing the payload')
71+
end
72+
end
73+
6074
context 'when token is not verified' do
6175
it 'raises an error' do
6276
expect { token.payload }.to raise_error(JWT::DecodeError, 'Verify the token signature before accessing the payload')

0 commit comments

Comments
 (0)