Skip to main content

How to Add Custom Claims to a JWT in Ruby with JWT.encode

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

With the jwt gem, custom claims are more keys in the payload hash you pass to JWT.encode, next to registered claims such as sub and exp. A string, an array and a hash become a JSON string, array and object, and JWT.decode gives them back with string keys.

Syntax​

Syntax
payload = {
'<registered claim>' => <value>,
'<custom claim>' => <value>
}
token = JWT.encode(payload, <key>, '<alg>')

claims, _header = JWT.decode(token, <key>, true, algorithm: '<alg>')
value = claims['<custom claim>']
PartWhat it does
'<registered claim>'A claim the JWT standard defines, such as sub or exp.
'<custom claim>'A name of your own: a short one such as name, or a URL on your own domain so that it can't collide with anyone else's.
<value>A string, a number, true or false, nil, an array such as ['editor', 'viewer'], or a hash such as { 'albums' => 10 }.
JWT.encode(...)Signs the payload with the key and returns the token.
JWT.decode(...)Verifies the token and returns its claims and its header. true turns verification on, and algorithm: names the one algorithm to accept.
claims['<custom claim>']Reads a claim. Decoded claims always have string keys.

RFC 7519, the JWT standard, says that "Claim Names can be defined at will by those using JWTs", and that to prevent collisions a new name should be registered with IANA or be "a value that contains a Collision-Resistant Name", such as a URL on a domain you control. The ruby-jwt README says to "specify the algorithm in the options hash whenever you call JWT.decode".

The Example​

The example signs a token for Ada at a photo site. Besides four registered claims, it carries three custom claims of three kinds: name, a string; roles, an array; and https://photos.example.org/quota, a hash, named with a URL on the site's own domain. The code prints the token, verifies it, prints the claims it got back, then reads one value of each kind.

Prerequisites​

  • Ruby and Bundler, which comes with it. 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 a Gemfile, and bundle add jwt installs the gem, version 3.3.2 here.

Step 2: Write the Code​

Create main.rb:

main.rb, which builds a payload with iss, sub, aud and exp plus the custom claims name, roles and https://photos.example.org/quota, signs it with JWT.encode, prints the token, decodes it and prints the claims, then prints the name, the roles joined with a comma and the number of albums.

main.rb
require 'jwt'

# The signing key: 32 random bytes, written as base64.
# It's in the code only for this example; a real app loads it from its configuration.
key = 'C4iNOOORzmu+fnrPK29yq/9n92b/zf5mOs5KvOMaY64='.unpack1('m0')

payload = {
'iss' => 'https://login.example.org',
'sub' => 'ada',
'aud' => 'https://photos.example.org',
'exp' => Time.now.to_i + 3600,
'name' => 'Ada', # a string
'roles' => ['editor', 'viewer'], # an array
'https://photos.example.org/quota' => { 'albums' => 10, 'storage_gb' => 50 } # a hash
}
token = JWT.encode(payload, key, 'HS256')
puts token

claims, _header = JWT.decode(token, key, true, algorithm: 'HS256')
p claims

quota = claims['https://photos.example.org/quota']
puts "#{claims['name']} | #{claims['roles'].join(', ')} | #{quota['albums']}"
  • 'name' => 'Ada' is a string claim.
  • 'roles' => ['editor', 'viewer'] is an array, which ruby-jwt writes as a JSON array.
  • 'https://photos.example.org/quota' => { ... } is a hash, which ruby-jwt writes as a JSON object. Its name is a URL on the photo site's own domain.
  • JWT.decode(token, key, true, algorithm: 'HS256') verifies the signature and exp, and returns the claims and the header, of which _header takes the second.
  • claims['https://photos.example.org/quota'] reads the claim whose name is a URL, like any other key.

Step 3: Run It​

Terminal
bundle exec ruby main.rb
Output
eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2xvZ2luLmV4YW1wbGUub3JnIiwic3ViIjoiYWRhIiwiYXVkIjoiaHR0cHM6Ly9waG90b3MuZXhhbXBsZS5vcmciLCJleHAiOjE3OTYyOTk4NTUsIm5hbWUiOiJBZGEiLCJyb2xlcyI6WyJlZGl0b3IiLCJ2aWV3ZXIiXSwiaHR0cHM6Ly9waG90b3MuZXhhbXBsZS5vcmcvcXVvdGEiOnsiYWxidW1zIjoxMCwic3RvcmFnZV9nYiI6NTB9fQ.kYZYtXGgOKjljuthn1OA4AGqOYh3pEvfVs1TKTyFEm4
{"iss" => "https://login.example.org", "sub" => "ada", "aud" => "https://photos.example.org", "exp" => 1796299855, "name" => "Ada", "roles" => ["editor", "viewer"], "https://photos.example.org/quota" => {"albums" => 10, "storage_gb" => 50}}
Ada | editor, viewer | 10

A zsh terminal where bundle exec ruby main.rb prints the token, then a hash with iss, sub, aud, exp, name Ada, roles editor and viewer, and the quota hash with albums 10 and storage_gb 50, then Ada, editor, viewer and 10 separated by bars.

The command is the same in zsh, bash and PowerShell.

What Happened​

  • The claims came back with their Ruby types: "name" => "Ada", "roles" => ["editor", "viewer"], and the quota as a hash, {"albums" => 10, "storage_gb" => 50}.
  • Every key came back as a string, the nested ones included, because the keys of a JSON object are strings.
  • JWT.decode accepted the token: the signature matched and exp wasn't past.

Inside the token, the payload (its middle piece) holds the JSON "roles":["editor","viewer"] and "https://photos.example.org/quota":{"albums":10,"storage_gb":50}. In separate checks, a float, true, an integer and nil came back with their types, as 2.5, true, 10 and nil.

Common Mistakes​

MistakeWhat happensDo this instead
Reading a claim with a symbol, as in claims[:name]It's nil: decoded claims have string keys, even when the payload used symbolsRead claims['name']
A Time as a claim's valueruby-jwt writes it as text, "2026-01-02 03:04:05 UTC", and it comes back as a StringWrite the time as Unix seconds with .to_i
A symbol as a claim's value, such as :proIt comes back as the string "pro"Compare the claim with strings after decoding
A hash with integer keys, such as { 1 => 'a' }The keys come back as strings: {"1" => "a"}Use string keys
NaN or Infinity as a claim's value, such as the result of 0.0 / 0JWT.encode stops with NaN not allowed in JSON (JSON::GeneratorError)Check the number with finite? first

Troubleshooting​

SymptomLikely causeFix
undefined method 'join' for nil (NoMethodError) after decodingThe token has no roles claimGive it a default: claims.fetch('roles', []).join(', ') gave ""
NaN not allowed in JSON (JSON::GeneratorError) from JWT.encodeA claim's value is NaN or Infinity, which JSON can't holdAdd the claim only when finite? is true for the number
Signature has expired (JWT::ExpiredSignature)exp is in the pastSign a new token, with exp in the future

FAQ​

Should every custom claim be named with a URL?​

No. A URL on your own domain is for claims that other services might name the same way. RFC 7519 also allows Private Names that only the token's producer and consumer agree on, such as name and roles here, but it warns that, unlike public names, they're "subject to collision and should be used with caution".

Can I use symbol keys in the payload?​

Yes. JWT.encode accepted { sub: 'ada', name: 'Ada', quota: { albums: 10 } }. The claims came back with string keys, though: claims['name'] was "Ada" and claims[:name] was nil, and the nested albums was the same.

Does JWT.decode check the custom claims?​

No. It checks the signature and the times, such as exp; whether a custom claim is there, with the type you expect, is up to your code. In my check, a token without roles passed JWT.decode, and the code then stopped at claims['roles'].join(', ').

Conclusion​

In ruby-jwt, custom claims are keys in the payload hash, and Ruby's strings, arrays and hashes become JSON strings, arrays and objects. Name a claim with a URL on your own domain when it might collide, read it back with a string key, and check that it's there before you rely on it.

Additional Resources​