diff --git a/lib/jwt/decode.rb b/lib/jwt/decode.rb index 784f6719..486acefe 100644 --- a/lib/jwt/decode.rb +++ b/lib/jwt/decode.rb @@ -47,10 +47,17 @@ def options_includes_algo_in_header? end def allowed_algorithms - if @options.key?(:algorithm) + # Order is very important - first check for string keys, next for symbols + if @options.key?('algorithm') + [@options['algorithm']] + elsif @options.key?(:algorithm) [@options[:algorithm]] - else + elsif @options.key?('algorithms') + @options['algorithms'] || [] + elsif @options.key?(:algorithms) @options[:algorithms] || [] + else + [] end end diff --git a/spec/jwt_spec.rb b/spec/jwt_spec.rb index 5156d7a4..e9b47359 100644 --- a/spec/jwt_spec.rb +++ b/spec/jwt_spec.rb @@ -122,6 +122,13 @@ expect(jwt_payload).to eq payload end + it 'should decode a valid token using algorithm hash string key' do + jwt_payload, header = JWT.decode data[alg], data[:rsa_public], true, 'algorithm' => alg + + expect(header['alg']).to eq alg + expect(jwt_payload).to eq payload + end + it 'wrong key should raise JWT::DecodeError' do key = OpenSSL::PKey.read File.read(File.join(CERT_PATH, 'rsa-2048-wrong-public.pem')) @@ -312,6 +319,12 @@ # unsuccessful keyfinder public key network call here end end.to raise_error JWT::IncorrectAlgorithm + + expect do + JWT.decode(token, nil, true, { 'algorithms' => ['RS384'] }) do |_,_| + # unsuccessful keyfinder public key network call here + end + end.to raise_error JWT::IncorrectAlgorithm end it 'should raise JWT::IncorrectAlgorithm when algorithms array does not contain algorithm' do @@ -321,9 +334,17 @@ JWT.decode token, data[:secret], true, algorithms: ['HS384'] end.to raise_error JWT::IncorrectAlgorithm + expect do + JWT.decode token, data[:secret], true, 'algorithms' => ['HS384'] + end.to raise_error JWT::IncorrectAlgorithm + expect do JWT.decode token, data[:secret], true, algorithms: ['HS512', 'HS384'] end.not_to raise_error + + expect do + JWT.decode token, data[:secret], true, 'algorithms' => ['HS512', 'HS384'] + end.not_to raise_error end context 'no algorithm provided' do