diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a0d71fa..4c8c32bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ - Fix compatibility with the openssl 4.0 gem [#706](https://github.com/jwt/ruby-jwt/pull/706) - Test against Ruby 4.0 on CI [#707](https://github.com/jwt/ruby-jwt/pull/707) +- Fix type error when header is not a JSON object [#715](https://github.com/jwt/ruby-jwt/pull/715) - ([@304](https://github.com/304)) - Your contribution here ## [v3.1.2](https://github.com/jwt/ruby-jwt/tree/v3.1.2) (2025-06-28) diff --git a/lib/jwt/decode.rb b/lib/jwt/decode.rb index 9a8a0a60..e6b8e74d 100644 --- a/lib/jwt/decode.rb +++ b/lib/jwt/decode.rb @@ -58,7 +58,7 @@ def verify_signature def verify_algo raise JWT::IncorrectAlgorithm, 'An algorithm must be specified' if allowed_algorithms.empty? - raise JWT::DecodeError, 'Token header not a JSON object' unless token.header.is_a?(Hash) + raise JWT::DecodeError, 'Token header not a JSON object' unless valid_token_header? raise JWT::IncorrectAlgorithm, 'Token is missing alg header' unless alg_in_header raise JWT::IncorrectAlgorithm, 'Expected a different algorithm' if allowed_and_valid_algorithms.empty? end @@ -113,9 +113,15 @@ def validate_segment_count! end def none_algorithm? + return false unless valid_token_header? + alg_in_header == 'none' end + def valid_token_header? + token.header.is_a?(Hash) + end + def alg_in_header token.header['alg'] end diff --git a/spec/jwt/jwt_spec.rb b/spec/jwt/jwt_spec.rb index 1bc14e0e..d4ccc23e 100644 --- a/spec/jwt/jwt_spec.rb +++ b/spec/jwt/jwt_spec.rb @@ -8,6 +8,7 @@ :empty_token => 'e30K.e30K.e30K', :empty_token_2_segment => 'e30K.e30K.', :invalid_header_token => 'W10.e30K.e30K', + :invalid_2_segment_header_token => 'WyJIUzI1NiJd.e30K', :secret => 'My$ecretK3y', :rsa_private => test_pkey('rsa-2048-private.pem'), :rsa_public => test_pkey('rsa-2048-public.pem'), @@ -472,6 +473,14 @@ end end + context 'invalid 2-segment header format' do + it 'should raise JWT::DecodeError' do + expect do + JWT.decode data[:invalid_2_segment_header_token] + end.to raise_error JWT::DecodeError + end + end + context '2-segment token' do it 'should raise JWT::IncorrectAlgorithm' do expect do