From 1c2de2fca03701ae520b7f1ba6267a5f6080b061 Mon Sep 17 00:00:00 2001 From: Adam Greene Date: Thu, 17 Sep 2015 11:57:47 -0700 Subject: [PATCH] make sure :sub check behaves like :aud check if :verify_sub is turned on and options includes a :sub, make sure we fail if the payload is not set or doesn't match. Previously if the payload did not have 'sub' set, it would not verify, even if verify_sub was true --- lib/jwt.rb | 2 +- spec/jwt_spec.rb | 14 +++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) 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'