Skip to content

Commit

Permalink
Add an option to verify the signature on decode
Browse files Browse the repository at this point in the history
  • Loading branch information
javawizard committed Apr 1, 2015
1 parent 02703c7 commit 973edb0
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
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

0 comments on commit 973edb0

Please sign in to comment.