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

Add an option to verify the signature on decode #71

Merged
merged 1 commit into from
Apr 2, 2015
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
4 changes: 4 additions & 0 deletions lib/jwt.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ module JWT
class DecodeError < StandardError; end
class VerificationError < DecodeError; end
class ExpiredSignature < DecodeError; end
class IncorrectAlgorithm < DecodeError; end
class ImmatureSignature < DecodeError; end
class InvalidIssuerError < DecodeError; end
class InvalidIatError < DecodeError; end
Expand Down Expand Up @@ -122,6 +123,9 @@ def decode(jwt, key=nil, verify=true, options={}, &keyfinder)

if verify
algo, key = signature_algorithm_and_key(header, key, &keyfinder)
if options[:algorithm] && algo != options[:algorithm]
raise JWT::IncorrectAlgorithm.new('Expected a different algorithm')
end
verify_signature(algo, key, signing_input, signature)
end

Expand Down
10 changes: 10 additions & 0 deletions spec/jwt_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,16 @@
expect { JWT.encode(@payload, 'secret', 'HS1024') }.to raise_error(NotImplementedError)
end

it 'raises exception when decoded with a different algorithm than it was encoded with' do
jwt = JWT.encode(@payload, 'foo', 'HS384')
expect { JWT.decode(jwt, 'foo', true, algorithm: 'HS512') }.to raise_error(JWT::IncorrectAlgorithm)
end

it 'does not raise exception when encoded with the expected algorithm' do
jwt = JWT.encode(@payload, 'foo', 'HS512')
JWT.decode(jwt, 'foo', true, algorithm: 'HS512')
end

it 'encodes and decodes plaintext JWTs' do
jwt = JWT.encode(@payload, nil, nil)
expect(jwt.split('.').length).to eq(2)
Expand Down