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

Handle some invalid JWTs #22

Merged
merged 2 commits into from
Aug 26, 2013
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
5 changes: 4 additions & 1 deletion lib/jwt.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,13 @@ def decode(jwt, key=nil, verify=true, &keyfinder)
begin
header = MultiJson.decode(base64url_decode(header_segment))
payload = MultiJson.decode(base64url_decode(payload_segment))
signature = base64url_decode(crypto_segment) if verify
signature = base64url_decode(crypto_segment.to_s) if verify
rescue MultiJson::LoadError => e
raise JWT::DecodeError.new("Invalid segment encoding")
end

raise JWT::DecodeError.new("Not enough or too many segments") unless header && payload

if verify
algo = header["alg"]

Expand Down
17 changes: 16 additions & 1 deletion spec/jwt_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,21 @@
lambda { JWT.decode(jwt, bad_private_key.public_key) }.should raise_error(JWT::DecodeError)
end

it "raises exception with invalid signature" do
example_payload = {"hello" => "world"}
example_secret = 'secret'
example_jwt = 'eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJoZWxsbyI6ICJ3b3JsZCJ9.'
lambda { JWT.decode(example_jwt, example_secret) }.should raise_error(JWT::DecodeError)
end

it "raises exception with nonexistent header" do
lambda { JWT.decode("..stuff") }.should raise_error(JWT::DecodeError)
end

it "raises exception with nonexistent payload" do
lambda { JWT.decode("eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9..stuff") }.should raise_error(JWT::DecodeError)
end

it "allows decoding without key" do
right_secret = 'foo'
bad_secret = 'bar'
Expand Down Expand Up @@ -93,7 +108,7 @@
signature = JWT.base64url_decode(crypto_segment)
signature.should_not_receive('==')
JWT.should_receive(:base64url_decode).with(crypto_segment).once.and_return(signature)
JWT.should_receive(:base64url_decode).any_number_of_times.and_call_original
JWT.should_receive(:base64url_decode).at_least(:once).and_call_original

JWT.decode(jwt, secret)
end
Expand Down