Skip to content

Commit 94b8a43

Browse files
committed
Fix type error when header is not a JSON object
Prevent TypeError when decoding tokens with non-hash headers (e.g., arrays). Fixes a TypeError where malformed tokens with array headers caused "no implicit conversion of String into Integer" error instead of raising the expected JWT::DecodeError.
1 parent 8c655d4 commit 94b8a43

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
- Fix compatibility with the openssl 4.0 gem [#706](https://github.com/jwt/ruby-jwt/pull/706)
1414
- Test against Ruby 4.0 on CI [#707](https://github.com/jwt/ruby-jwt/pull/707)
15+
- Fix type error when header is not a JSON object [#715](https://github.com/jwt/ruby-jwt/pull/715) - ([@304](https://github.com/304))
1516
- Your contribution here
1617

1718
## [v3.1.2](https://github.com/jwt/ruby-jwt/tree/v3.1.2) (2025-06-28)

lib/jwt/decode.rb

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def verify_signature
5858

5959
def verify_algo
6060
raise JWT::IncorrectAlgorithm, 'An algorithm must be specified' if allowed_algorithms.empty?
61-
raise JWT::DecodeError, 'Token header not a JSON object' unless token.header.is_a?(Hash)
61+
raise JWT::DecodeError, 'Token header not a JSON object' unless valid_token_header?
6262
raise JWT::IncorrectAlgorithm, 'Token is missing alg header' unless alg_in_header
6363
raise JWT::IncorrectAlgorithm, 'Expected a different algorithm' if allowed_and_valid_algorithms.empty?
6464
end
@@ -113,9 +113,15 @@ def validate_segment_count!
113113
end
114114

115115
def none_algorithm?
116+
return false unless valid_token_header?
117+
116118
alg_in_header == 'none'
117119
end
118120

121+
def valid_token_header?
122+
token.header.is_a?(Hash)
123+
end
124+
119125
def alg_in_header
120126
token.header['alg']
121127
end

spec/jwt/jwt_spec.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
:empty_token => 'e30K.e30K.e30K',
99
:empty_token_2_segment => 'e30K.e30K.',
1010
:invalid_header_token => 'W10.e30K.e30K',
11+
:invalid_2segment_header_token => 'WyJIUzI1NiJd.e30K',
1112
:secret => 'My$ecretK3y',
1213
:rsa_private => test_pkey('rsa-2048-private.pem'),
1314
:rsa_public => test_pkey('rsa-2048-public.pem'),
@@ -472,6 +473,14 @@
472473
end
473474
end
474475

476+
context 'invalid 2-segment header format' do
477+
it 'should raise JWT::DecodeError' do
478+
expect do
479+
JWT.decode data[:invalid_2_segment_header_token]
480+
end.to raise_error JWT::DecodeError
481+
end
482+
end
483+
475484
context '2-segment token' do
476485
it 'should raise JWT::IncorrectAlgorithm' do
477486
expect do

0 commit comments

Comments
 (0)