diff --git a/lib/jwt.rb b/lib/jwt.rb index d1e6249d..1b674742 100644 --- a/lib/jwt.rb +++ b/lib/jwt.rb @@ -176,7 +176,7 @@ def decode(jwt, key = nil, verify = true, options = {}, &keyfinder) fail(JWT::InvalidAudError, "Invalid audience. Expected #{options[:aud]}, received #{payload['aud'] || ''}") unless payload['aud'].to_s == options[:aud].to_s end end - if options[:verify_sub] && payload.include?('sub') + if options[:verify_sub] && options.include?(:sub) fail(JWT::InvalidSubError, "Invalid subject. Expected #{options[:sub]}, received #{payload['sub'] || ''}") unless payload['sub'].to_s == options[:sub].to_s end if options[:verify_jti] && payload.include?('jti') diff --git a/spec/jwt_spec.rb b/spec/jwt_spec.rb index 0377e1ac..ecf7a705 100644 --- a/spec/jwt_spec.rb +++ b/spec/jwt_spec.rb @@ -213,7 +213,19 @@ expect(decoded_payload).to include(example_payload) end - it 'raise decode exception when the sub is invalid' + it 'raises decode exception when verify_sub is set but the JWT does not contain a sub' do + example_payload = {'foo' => 'bar'} + example_secret = 'secret' + example_jwt = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmb28iOiJiYXIifQ.bVhBeMrW5g33Vi4FLSLn7aqcmAiupmmw-AY17YxCYLI' + expect { JWT.decode(example_jwt, example_secret, true, verify_sub: true, sub: 'subject') }.to raise_error(JWT::InvalidSubError) + end + + it 'raise decode exception when the sub does not match' do + example_payload = {'sub' => 'subject', 'foo' => 'bar'} + example_secret = 'secret' + example_jwt = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzdWJqZWN0IiwiZm9vIjoiYmFyIn0.RUkJZgPcK3eOU3iR301nsZa3MSA936fgu03_UoamVuo' + expect { JWT.decode(example_jwt, example_secret, true, verify_sub: true, sub: 'another_subject') }.to raise_error(JWT::InvalidSubError) + end it 'raises decode exception when the token is invalid' do example_secret = 'secret'