From 973edb087cc2d282f96ce43a6fa2ff282d44832d Mon Sep 17 00:00:00 2001 From: Alexander Boyd Date: Wed, 1 Apr 2015 13:33:23 -0600 Subject: [PATCH] Add an option to verify the signature on decode --- lib/jwt.rb | 4 ++++ spec/jwt_spec.rb | 10 ++++++++++ 2 files changed, 14 insertions(+) diff --git a/lib/jwt.rb b/lib/jwt.rb index 4f473208..8e9c00ef 100644 --- a/lib/jwt.rb +++ b/lib/jwt.rb @@ -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 @@ -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 diff --git a/spec/jwt_spec.rb b/spec/jwt_spec.rb index 5617a95a..a7e3885d 100644 --- a/spec/jwt_spec.rb +++ b/spec/jwt_spec.rb @@ -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)