Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix algorithm picking from decode options #359

Merged
merged 2 commits into from
Jul 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions lib/jwt/decode.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
21 changes: 21 additions & 0 deletions spec/jwt_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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'))

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down