Skip to main content

How to Verify a JWT in Ruby with JWT.decode

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

JWT.decode from the jwt gem verifies a JSON Web Token in Ruby. You pass the token, the key, true to verify, and the algorithm you accept, and it returns the payload and the header, or raises an error that says what's wrong.

Syntax​

Syntax
payload, header = JWT.decode(<token>, <key>, true, { algorithm: '<algorithm>' })
PartWhat it does
<token>The JWT string to check.
<key>The key to check the signature with: for HS256, the same secret that signed the token.
trueVerify the signature and the claims. false skips every check.
{ algorithm: '<algorithm>' }The algorithm you accept, such as 'HS256'. More options go in the same hash, such as leeway:.
payload, headerThe result: an array of the payload and the header, as hashes with string keys.

The jwt gem's README: "For safe cryptographic signing, you need to specify the algorithm in the options hash whenever you call JWT.decode to ensure that an attacker cannot bypass the algorithm verification step. It is strongly recommended that you hard code the algorithm, as you may leave yourself vulnerable by dynamically picking the algorithm".

The Example​

The example signs a token for the user ada with the role reader, then decodes it twice: with the key that signed it, and with a different key, the way a token from another app would arrive.

Both keys are 32 random bytes, made with openssl rand -base64 32 and written as base64. They sit in the code only so the example runs as it is. A real application loads its key from configuration and never keeps it in the source.

Prerequisites​

  • Ruby with Bundler. This guide uses Ruby 4.0.10 and Bundler 4.1.0.

Step 1: Create the Project​

Terminal
mkdir demo
cd demo
bundle init
bundle add jwt

bundle init writes an empty Gemfile, and bundle add jwt adds the gem, 3.3.1 here, and installs it.

Step 2: Write the Code​

Create main.rb:

main.rb, which signs a token for ada with role reader and a 10-minute expiry, decodes it with JWT.decode, the key, true and algorithm HS256 into payload and header, puts both, then decodes it with another key and rescues JWT::VerificationError to print Rejected with the message.

main.rb
require 'jwt'

# Two keys, 32 random bytes each, written as base64.
# They're in the code only for this example; a real app loads its key from its configuration.
key = 'VfosHbT9z3nikPe56UUfKL9Y6mF2oOui09j4GCY0AYs='.unpack1('m0')
other_key = 'rAAk7yhJl8rF7vvQeKOeI2ooYrBw9A45aLuMb44gH78='.unpack1('m0')

token = JWT.encode({ sub: 'ada', role: 'reader', exp: Time.now.to_i + 600 }, key, 'HS256')

payload, header = JWT.decode(token, key, true, { algorithm: 'HS256' })
puts payload
puts header

begin
JWT.decode(token, other_key, true, { algorithm: 'HS256' })
rescue JWT::VerificationError => e
puts "Rejected: #{e.message}"
end

JWT.decode returns a two-item array, so multiple assignment puts the payload in payload and the header in header.

Step 3: Run It​

Terminal
bundle exec ruby main.rb
Output
{"sub" => "ada", "role" => "reader", "exp" => 1795683146}
{"alg" => "HS256"}
Rejected: Signature verification failed

A zsh terminal where bundle exec ruby main.rb prints the payload hash with sub ada, role reader and exp, the header hash with alg HS256, then Rejected: Signature verification failed.

With the right key, decode checked the signature and the exp claim and returned both hashes. Their keys are strings, though the payload was written with symbols. With the other key, the signature didn't match, so it raised JWT::VerificationError.

The Errors It Raises​

These came from real runs. Each of them inherits from JWT::DecodeError, through JWT::TokenError, so one rescue JWT::DecodeError catches every bad token:

What's wrongErrorMessage
Signed with another key, or the payload was changedJWT::VerificationErrorSignature verification failed
The token has expiredJWT::ExpiredSignatureSignature has expired
Signed with HS256, but algorithm: 'HS512'JWT::IncorrectAlgorithmExpected a different algorithm
Not a JWT at allJWT::MalformedTokenErrorNot enough or too many segments

Allow a Little Clock Skew​

Add leeway: to the options: with { algorithm: 'HS256', leeway: 60 }, a token that had expired 30 seconds earlier still decoded.

Common Mistakes​

MistakeWhat happensDo this instead
Passing false as the third argumentNo check at all: a token decoded with false and the wrong key came back as if validAlways pass true
Leaving out the algorithm optionThe gem falls back to its default, ['HS256']: an HS256 token decoded, and an HS384 token raised Expected a different algorithmPass the algorithm anyway, as the README says, so the code states what it accepts
Reading payload[:sub]nil: the keys are stringsRead payload['sub']

Troubleshooting​

SymptomLikely causeFix
Signature verification failedAnother key signed it, or it was changedCheck with the signing key; reject the token
Signature has expiredThe exp has passedGet a new token, or add a small leeway
Expected a different algorithmThe token's algorithm differs from the algorithm optionSign and verify with the same algorithm

FAQ​

What does JWT.decode return?​

An array of two hashes, the payload first and the header second, as the README shows.

Does decode check the expiry?​

Yes, when the third argument is true and the token has an exp claim.

Conclusion​

JWT.decode(token, key, true, { algorithm: 'HS256' }) verifies the signature and the time claims and returns the payload and the header. Always pass true and a hard-coded algorithm, read claims with string keys, and rescue JWT::DecodeError for every bad token.

Additional Resources​