JWT

suggest change

A JSON Web Token (JWT, RFC 7519) is a compact, URL-safe string that carries a set of claims ("user 42, role admin, valid until 10:15") plus a signature. Whoever holds the signing key can issue tokens. Anyone holding the verification key can check that a token is genuine and hasn't been changed, without a database lookup. That makes JWTs a popular choice for API access tokens, single sign-on (OpenID Connect ID tokens) and short-lived links between services.

A JWT has three base64url-encoded parts separated by dots:

Part Contains Example (decoded)
Header signing algorithm, optional key id {"alg":"HS256","kid":"2026-10"}
Payload the claims {"sub":"42","exp":1792264910}
Signature signature over header.payload 32 bytes of HMAC-SHA256

The payload is signed, not encrypted. Anyone who gets the token can read it, so never put passwords, card numbers or other secrets in it.

In Ruby the standard library is the jwt gem:

gem install jwt

The examples were run with Ruby 4.0, jwt 3.3, Sinatra 4.2 and rack-test 2.2. The Authentication article gives a short overview of tokens next to other login methods. This article goes into JWT in depth.

A JWT built by hand

To see that there is no magic, here is a token built with only openssl, base64 and json:

require 'openssl'
require 'base64'
require 'json'

def b64url(data) = Base64.urlsafe_encode64(data, padding: false)

secret  = 'my-signing-secret-that-is-at-least-32-bytes'
header  = { alg: 'HS256', typ: 'JWT' }
payload = { sub: '42', name: 'Alice', admin: false, exp: 1_900_000_000 }

signing_input = "#{b64url(header.to_json)}.#{b64url(payload.to_json)}"
signature     = OpenSSL::HMAC.digest('SHA256', secret, signing_input)
token         = "#{signing_input}.#{b64url(signature)}"

puts token.split('.')
puts

# Anyone can read the header and payload - they are only encoded, not encrypted
h, p, _sig = token.split('.')
puts Base64.urlsafe_decode64(h)
puts Base64.urlsafe_decode64(p)
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
eyJzdWIiOiI0MiIsIm5hbWUiOiJBbGljZSIsImFkbWluIjpmYWxzZSwiZXhwIjoxOTAwMDAwMDAwfQ
esGJyZLFCki9z09DGMHxrY5cJihJyoTGJT-3MVXCWcA

{"alg":"HS256","typ":"JWT"}
{"sub":"42","name":"Alice","admin":false,"exp":1900000000}

Base64.urlsafe_encode64(..., padding: false) gives the URL-safe alphabet (- and _ instead of + and /) without = padding, which is what JWTs use (see Base64 and hex encoding). Verifying is the same computation: recompute the HMAC over the first two parts and compare it to the third in constant time.

Don't write your own verifier for production. Verification has to check the algorithm, the key type, the signature and the time claims, and libraries have had serious bugs in each of these. Use the gem.

Encoding and decoding with the jwt gem

JWT.encode(payload, key, algorithm, extra_headers) returns the token string. JWT.decode(token, key, verify, options) verifies it and returns a two-element array [payload, header]:

require 'jwt'

SECRET = ENV.fetch('JWT_SECRET') { 'dev-only-secret-0123456789abcdef0123456789' }

now = Time.now.to_i
payload = {
  sub: '42',            # subject: who the token is about
  iss: 'https://auth.example.com',
  aud: 'orders-api',
  iat: now,             # issued at
  nbf: now,             # not valid before
  exp: now + 15 * 60,   # expires in 15 minutes
  jti: 'b7f3c1d2',      # unique token id
  roles: %w[reader writer]
}

token = JWT.encode(payload, SECRET, 'HS256', { typ: 'JWT' })
puts token.length

decoded_payload, header = JWT.decode(
  token, SECRET, true,
  algorithm: 'HS256',
  iss: 'https://auth.example.com', verify_iss: true,
  aud: 'orders-api', verify_aud: true,
  required_claims: %w[sub exp]
)

p header
p decoded_payload.slice('sub', 'roles')
p decoded_payload.keys
p decoded_payload['exp'] - decoded_payload['iat']
295
{"typ" => "JWT", "alg" => "HS256"}
{"sub" => "42", "roles" => ["reader", "writer"]}
["sub", "iss", "aud", "iat", "nbf", "exp", "jti", "roles"]
900

Things to notice:

Registered claims

RFC 7519 defines short names for the common claims:

Claim Meaning Checked by JWT.decode
iss issuer: who created the token with iss: and verify_iss: true
sub subject: usually the user id, as a string with sub: and verify_sub: true
aud audience: which service the token is for (string or array) with aud: and verify_aud: true
exp expiration time always (turn off with verify_expiration: false)
nbf not valid before always (turn off with verify_not_before: false)
iat issued at with verify_iat: true (rejects iat in the future)
jti unique token id, used for revocation or replay checks with verify_jti: true or a proc

Anything else (roles, tenant_id, scope) is a private claim. Keep them few and small: the token is sent with every request.

Handling invalid tokens

Every failure raises a subclass of JWT::DecodeError, so one rescue covers them all. The specific classes let you give a better message, for example telling a client that its token expired so it knows to refresh:

require 'jwt'
require 'base64'

SECRET = 'dev-only-secret-0123456789abcdef0123456789'
OPTS = { algorithm: 'HS256', iss: 'auth', verify_iss: true,
         aud: 'orders-api', verify_aud: true }

def check(label, token, key: SECRET, **opts)
  payload, = JWT.decode(token, key, true, OPTS.merge(opts))
  puts "#{label}: ok sub=#{payload['sub']}"
rescue JWT::DecodeError => e
  puts "#{label}: #{e.class} - #{e.message}"
end

now  = Time.now.to_i
good = { sub: '42', iss: 'auth', aud: 'orders-api', exp: now + 60 }

check 'valid',          JWT.encode(good, SECRET, 'HS256')
check 'expired',        JWT.encode(good.merge(exp: now - 10), SECRET, 'HS256')
check 'expired+leeway', JWT.encode(good.merge(exp: now - 10), SECRET, 'HS256'), leeway: 30
check 'not yet valid',  JWT.encode(good.merge(nbf: now + 300), SECRET, 'HS256')
check 'wrong issuer',   JWT.encode(good.merge(iss: 'evil'), SECRET, 'HS256')
check 'wrong audience', JWT.encode(good.merge(aud: 'billing'), SECRET, 'HS256')
check 'wrong key',      JWT.encode(good, 'another-secret-0123456789abcdef01234', 'HS256')
check 'wrong alg',      JWT.encode(good, SECRET, 'HS512')
check 'missing claim',  JWT.encode(good.except(:sub), SECRET, 'HS256'), required_claims: ['sub']
check 'garbage',        'not.a.jwt'
check 'two segments',   'abc.def'

tampered = JWT.encode(good, SECRET, 'HS256').split('.')
tampered[1] = Base64.urlsafe_encode64(good.merge(sub: '1').to_json, padding: false)
check 'tampered',       tampered.join('.')
valid: ok sub=42
expired: JWT::ExpiredSignature - Signature has expired
expired+leeway: ok sub=42
not yet valid: JWT::ImmatureSignature - Signature nbf has not been reached
wrong issuer: JWT::InvalidIssuerError - Invalid issuer. Expected ["auth"], received evil
wrong audience: JWT::InvalidAudError - Invalid audience. Expected orders-api, received billing
wrong key: JWT::VerificationError - Signature verification failed
wrong alg: JWT::IncorrectAlgorithm - Expected a different algorithm
missing claim: JWT::MissingRequiredClaim - Missing required claim sub
garbage: JWT::Base64DecodeError - Invalid base64 encoding
two segments: JWT::MalformedTokenError - Invalid segment encoding
tampered: JWT::VerificationError - Signature verification failed

leeway: (in seconds) allows for clock drift between the server that issued the token and the one checking it. A few seconds to a minute is typical. It applies to exp and nbf (exp_leeway: and nbf_leeway: set them separately).

The exception tree, from the gem's error.rb:

JWT::DecodeError
├── JWT::TokenError
│   ├── JWT::MalformedTokenError      (Base64DecodeError)
│   ├── JWT::SignatureError
│   │   ├── JWT::VerificationError    (bad signature, wrong key)
│   │   └── JWT::IncorrectAlgorithm   (alg not in your allow-list)
│   └── JWT::ClaimValidationError
│       ├── ExpiredSignature, ImmatureSignature
│       ├── InvalidIssuerError, InvalidAudError, InvalidSubError
│       ├── InvalidIatError, InvalidJtiError
│       └── MissingRequiredClaim
└── JWT::JWKError

Choosing an algorithm

Algorithm Key Use when
HS256 / HS384 / HS512 one shared secret (HMAC) the same application issues and verifies tokens
RS256 / PS256 RSA key pair (3072+ bits) many services verify, only one issues; needed by many identity providers
ES256 EC P-256 key pair like RSA but with much smaller keys and tokens
EdDSA Ed25519 key pair supported through the separate jwt-eddsa gem in jwt 3.x

With HMAC, every service that can verify a token can also forge one, because it holds the same secret. Use a random secret of at least 32 bytes (SecureRandom.hex(32)), never a word or a password. With an asymmetric algorithm, only the auth server holds the private key, and the public key can be handed out to anyone:

require 'jwt'
require 'openssl'

# In production, load keys from files or a secret manager:
#   private_key = OpenSSL::PKey.read(File.read('jwt_private.pem'))
rsa = OpenSSL::PKey::RSA.generate(3072)
ec  = OpenSSL::PKey::EC.generate('prime256v1')

# The public key can be shared freely with every service that verifies tokens
rsa_public_pem = rsa.public_to_pem
ec_public      = OpenSSL::PKey.read(ec.public_to_pem)

payload = { sub: '42', exp: Time.now.to_i + 600 }

rs_token = JWT.encode(payload, rsa, 'RS256')
ps_token = JWT.encode(payload, rsa, 'PS256')
es_token = JWT.encode(payload, ec, 'ES256')

puts "RS256 token: #{rs_token.size} chars"
puts "PS256 token: #{ps_token.size} chars"
puts "ES256 token: #{es_token.size} chars"

verifier = OpenSSL::PKey.read(rsa_public_pem)
p JWT.decode(rs_token, verifier, true, algorithm: 'RS256').first
p JWT.decode(ps_token, verifier, true, algorithm: 'PS256').first['sub']
p JWT.decode(es_token, ec_public, true, algorithm: 'ES256').first['sub']

# The public key cannot sign
begin
  JWT.encode(payload, verifier, 'RS256')
rescue => e
  puts "#{e.class}: #{e.message}"
end

# Algorithm confusion: attacker signs with HS256 using the public PEM as the secret
forged = JWT.encode({ sub: '1', admin: true }, rsa_public_pem, 'HS256')
begin
  JWT.decode(forged, verifier, true, algorithm: 'RS256')
rescue JWT::DecodeError => e
  puts "forged: #{e.class} - #{e.message}"
end
RS256 token: 573 chars
PS256 token: 573 chars
ES256 token: 147 chars
{"sub" => "42", "exp" => 1792265089}
"42"
"42"
JWT::EncodeError: The given key is not a private key
forged: JWT::IncorrectAlgorithm - Expected a different algorithm

ES256 tokens are a quarter of the size of RS256 ones, which matters when a token rides along in every request header. See Cryptography for more on generating and storing keys with OpenSSL.

The last part of the example is the classic algorithm confusion attack. A server that verifies with an RSA public key, but trusts whatever alg the token's header names, can be tricked into running HMAC with the (public!) PEM text as the secret. The jwt gem refuses because algorithm: 'RS256' doesn't include HS256. Never put both HMAC and RSA/EC algorithms in one allow-list.

The "none" algorithm and unverified decoding

The JWT spec allows "alg": "none", meaning "no signature". A library that honors it lets anyone write their own claims. The gem only accepts none if you explicitly list it, which you should never do:

require 'jwt'
require 'base64'
require 'json'

SECRET = 'dev-only-secret-0123456789abcdef0123456789'

# An attacker builds an unsigned token: {"alg":"none"} and an empty signature
b64 = ->(h) { Base64.urlsafe_encode64(h.to_json, padding: false) }
forged = "#{b64.({ alg: 'none' })}.#{b64.({ sub: '1', admin: true })}."

begin
  JWT.decode(forged, SECRET, true, algorithm: 'HS256')
rescue JWT::DecodeError => e
  puts "rejected: #{e.class} - #{e.message}"
end

# Reading a token WITHOUT verification - for logging/debugging only
token = JWT.encode({ sub: '42', exp: 0 }, SECRET, 'HS256')
payload, header = JWT.decode(token, nil, false)
p payload, header

# Same thing with the lower-level EncodedToken API
enc = JWT::EncodedToken.new(token)
p enc.header
p enc.unverified_payload
begin
  enc.payload
rescue JWT::DecodeError => e
  puts "#{e.class}: #{e.message}"
end
rejected: JWT::IncorrectAlgorithm - Expected a different algorithm
{"sub" => "42", "exp" => 0}
{"alg" => "HS256"}
{"alg" => "HS256"}
{"sub" => "42", "exp" => 0}
JWT::TokenError: Verify the token signature before accessing the payload

If you call JWT.decode without algorithm:, the gem uses the global default from JWT.configuration.decode.algorithms, which is ['HS256']. Relying on that is fragile. Say what you accept in every call.

JWT.decode(token, nil, false) skips all checks: signature, expiry, everything. It's fine for showing a token's contents in a debugging tool, or for reading the kid header before choosing a key. Never use its result for an access decision. The newer JWT::EncodedToken API enforces this: payload raises until the signature has been verified, while unverified_payload makes it obvious in code review that nothing was checked.

Step-by-step API: Token and EncodedToken

jwt 3.x also has an object API that splits signing, signature checks and claim checks into separate steps, and has non-raising variants for each:

require 'jwt'

SECRET = 'dev-only-secret-0123456789abcdef0123456789'

# Build and sign
token = JWT::Token.new(payload: { sub: '42', aud: 'api', exp: Time.now.to_i + 60 },
                       header: { kid: 'k1' })
token.sign!(algorithm: 'HS256', key: SECRET)
jwt = token.jwt
puts jwt.count('.')

# Parse and verify in explicit steps
enc = JWT::EncodedToken.new(jwt)
p enc.header
enc.verify_signature!(algorithm: 'HS256', key: SECRET)
enc.verify_claims!(:exp, aud: 'api', required: %w[sub])
p enc.payload

# Non-raising variants
p enc.valid_claims?(aud: 'billing')
p enc.claim_errors(:exp, aud: 'billing', iss: 'auth').map(&:message)

other = JWT::EncodedToken.new(jwt)
p other.valid_signature?(algorithm: 'HS256', key: 'wrong-secret-0123456789abcdef0123456')
2
{"kid" => "k1", "alg" => "HS256"}
{"sub" => "42", "aud" => "api", "exp" => 1792264549}
false
["Invalid audience. Expected billing, received api", "Invalid issuer. Expected [\"auth\"], received <none>"]
false

claim_errors returns every failed check at once instead of stopping at the first, which is handy for logs and tests.

Key rotation with kid

Secrets should change from time to time, and tokens already handed out shouldn't all break when they do. Put a key id in the header (kid) and keep a table of keys. Sign with the newest key, and keep accepting the older ones until the longest-lived token signed with them has expired. Pass a block to JWT.decode and it is called with the header to look up the key:

require 'jwt'

# Several HMAC secrets, identified by kid. Sign with the newest,
# keep accepting the older one until its tokens have expired.
KEYS = {
  '2026-09' => 'old-secret-0123456789abcdef0123456789abcdef',
  '2026-10' => 'new-secret-0123456789abcdef0123456789abcdef'
}.freeze
CURRENT_KID = '2026-10'

def issue(sub, kid: CURRENT_KID)
  JWT.encode({ sub: sub, exp: Time.now.to_i + 900 }, KEYS.fetch(kid), 'HS256', { kid: kid })
end

def verify(token)
  payload, header = JWT.decode(token, nil, true, algorithm: 'HS256') do |hdr|
    KEYS[hdr['kid']] # nil => JWT::SignatureError
  end
  "#{payload['sub']} (kid #{header['kid']})"
rescue JWT::DecodeError => e
  "#{e.class}: #{e.message}"
end

puts verify(issue('alice'))
puts verify(issue('bob', kid: '2026-09'))
puts verify(JWT.encode({ sub: 'eve' }, 'x' * 40, 'HS256', { kid: '1999-01' }))
alice (kid 2026-10)
bob (kid 2026-09)
JWT::SignatureError: No verification key available

JWKS: publishing public keys

For asymmetric keys the standard format is a JSON Web Key Set (JWKS, RFC 7517), usually served at /.well-known/jwks.json. Auth0, Okta, Keycloak, Google and Microsoft Entra ID all publish one. JWT::JWK converts between OpenSSL keys and JWK hashes, and computes a kid from the key's thumbprint:

require 'jwt'
require 'openssl'
require 'json'

# --- Auth server: holds the private keys ---
old_jwk = JWT::JWK.new(OpenSSL::PKey::EC.generate('prime256v1'), { use: 'sig', alg: 'ES256' })
new_jwk = JWT::JWK.new(OpenSSL::PKey::EC.generate('prime256v1'), { use: 'sig', alg: 'ES256' })

def sign(jwk, claims)
  JWT.encode(claims, jwk.signing_key, 'ES256', { kid: jwk[:kid] })
end

old_token = sign(old_jwk, { sub: 'alice', exp: Time.now.to_i + 600 })
new_token = sign(new_jwk, { sub: 'bob',   exp: Time.now.to_i + 600 })

# Publish only the public parts, e.g. at /.well-known/jwks.json
jwks_json = JWT::JWK::Set.new([old_jwk, new_jwk]).export.to_json
doc = JSON.parse(jwks_json)
puts doc['keys'].first.keys.inspect
puts "private 'd' present? #{jwks_json.include?('"d"')}"

# --- API server: knows only the published JWKS ---
jwks = JWT::JWK::Set.new(JSON.parse(jwks_json))

[old_token, new_token].each do |t|
  payload, header = JWT.decode(t, nil, true, algorithms: ['ES256'], jwks: jwks)
  puts "#{payload['sub']} verified with kid #{header['kid'][0, 12]}..."
end

# A token signed by a key that is not in the set
stranger = JWT::JWK.new(OpenSSL::PKey::EC.generate('prime256v1'))
begin
  JWT.decode(sign(stranger, { sub: 'mallory' }), nil, true, algorithms: ['ES256'], jwks: jwks)
rescue JWT::DecodeError => e
  puts "#{e.class}: #{e.message}"
end
["kty", "crv", "x", "y", "use", "alg", "kid"]
private 'd' present? false
alice verified with kid 502338eb2ed2...
bob verified with kid f1768ba68695...
JWT::SignatureError: Could not find public key for kid 12dbc07090779943c1f42d4fb0e557b3e78816d8b4379622a230ea54e29c43e3

export writes only the public fields (x, y for EC, n, e for RSA). Pass export(include_private: true) only when you deliberately store the private key as a JWK.

Fetching and caching a remote JWKS

When you verify tokens from an external identity provider, fetch its JWKS and cache it. The jwks: option also accepts any object with a call(options) method. The gem calls it again with options[:kid_not_found] == true when a token names a kid the cached set doesn't have. That's the moment to refetch, because the provider has probably rotated its keys:

require 'jwt'
require 'openssl'
require 'json'

# Stand-in for the identity provider. In real code fetch_jwks would do
#   JSON.parse(Net::HTTP.get(URI('https://auth.example.com/.well-known/jwks.json')))
$published = []
def fetch_jwks
  puts '  (fetching JWKS over HTTP)'
  JWT::JWK::Set.new($published).export
end

class JwksCache
  def initialize(ttl: 300, min_refetch: 30)
    @ttl = ttl
    @min_refetch = min_refetch
    @jwks = nil
    @fetched_at = Time.at(0)
  end

  # The jwt gem calls this with an options hash; options[:kid_not_found] is
  # true when the token's kid is missing from the set we returned last time.
  def call(options)
    age = Time.now - @fetched_at
    refetch = options[:kid_not_found] && age >= @min_refetch # throttle refetches
    if @jwks.nil? || age > @ttl || refetch
      @jwks = fetch_jwks
      @fetched_at = Time.now
    end
    @jwks
  end
end

def verify(token, cache)
  payload, = JWT.decode(token, nil, true, algorithms: ['ES256'], jwks: cache)
  puts "  ok: #{payload['sub']}"
rescue JWT::DecodeError => e
  puts "  #{e.class}: #{e.message[0, 40]}"
end

def issue(jwk, sub) = JWT.encode({ sub: sub }, jwk.signing_key, 'ES256', { kid: jwk[:kid] })

key1 = JWT::JWK.new(OpenSSL::PKey::EC.generate('prime256v1'))
$published = [key1]
cache = JwksCache.new(min_refetch: 0) # no throttling, to keep the demo short

puts 'first request:';  verify(issue(key1, 'alice'), cache)
puts 'second request:'; verify(issue(key1, 'alice'), cache)

# The provider rotates keys and starts signing with a new kid
key2 = JWT::JWK.new(OpenSSL::PKey::EC.generate('prime256v1'))
$published = [key1, key2]
puts 'token with new kid:'; verify(issue(key2, 'bob'), cache)

# An unknown kid that the provider never published
rogue = JWT::JWK.new(OpenSSL::PKey::EC.generate('prime256v1'))
puts 'rogue token:'; verify(issue(rogue, 'mallory'), cache)
first request:
  (fetching JWKS over HTTP)
  ok: alice
second request:
  ok: alice
token with new kid:
  (fetching JWKS over HTTP)
  ok: bob
rogue token:
  (fetching JWKS over HTTP)
  JWT::SignatureError: Could not find public key for kid b64c7e

The rogue token shows why the refetch is throttled (the min_refetch default of 30 seconds). Without that limit, an attacker could send a stream of tokens with made-up kids and make your server hammer the identity provider.

A JWT-protected API with refresh tokens and logout

A signed token can't be "taken back": it stays valid until exp. The usual design deals with that in three ways:

Here is that design in a small Sinatra app:

# api.rb
require 'sinatra/base'
require 'jwt'
require 'json'
require 'securerandom'
require 'digest'

module Tokens
  SECRET     = ENV.fetch('JWT_SECRET') { SecureRandom.hex(32) }
  ISSUER     = 'https://api.example.com'
  ACCESS_TTL = 15 * 60

  # Server-side state. Use Redis or a database table in production.
  REFRESH = {}  # sha256(refresh token) => { user_id:, expires_at: }
  REVOKED = {}  # jti => exp, so entries can be purged once the token expires

  module_function

  def issue_access(user_id, roles)
    now = Time.now.to_i
    claims = { sub: user_id.to_s, iss: ISSUER, aud: 'api', iat: now,
               exp: now + ACCESS_TTL, jti: SecureRandom.uuid, roles: roles }
    JWT.encode(claims, SECRET, 'HS256', { typ: 'JWT' })
  end

  def issue_refresh(user_id)
    raw = SecureRandom.urlsafe_base64(32)  # opaque, not a JWT
    REFRESH[Digest::SHA256.hexdigest(raw)] = { user_id:, expires_at: Time.now + 30 * 86_400 }
    raw
  end

  def verify_access(token)
    payload, = JWT.decode(token, SECRET, true,
                          algorithm: 'HS256', iss: ISSUER, verify_iss: true,
                          aud: 'api', verify_aud: true,
                          required_claims: %w[sub exp jti])
    raise JWT::DecodeError, 'Token has been revoked' if REVOKED.key?(payload['jti'])

    payload
  end
end

USERS = { 'alice' => { id: 1, password: 's3cret', roles: ['admin'] },
          'bob'   => { id: 2, password: 'hunter2', roles: [] } }.freeze

class Api < Sinatra::Base
  set :host_authorization, permitted_hosts: [] # allow any Host in this demo
  before { content_type :json }

  helpers do
    def claims
      @claims ||= begin
        scheme, token = request.env['HTTP_AUTHORIZATION'].to_s.split(' ', 2)
        halt_json 401, 'missing bearer token' unless scheme&.casecmp?('Bearer') && token
        Tokens.verify_access(token)
      rescue JWT::ExpiredSignature
        halt_json 401, 'token expired'
      rescue JWT::DecodeError => e
        logger.info("rejected token: #{e.class}: #{e.message}")
        halt_json 401, 'invalid token' # don't tell the client why
      end
    end

    def halt_json(status, message)
      headers 'WWW-Authenticate' => %(Bearer error="invalid_token") if status == 401
      halt status, { error: message }.to_json
    end

    def tokens_for(user_id, roles)
      { access_token: Tokens.issue_access(user_id, roles), token_type: 'Bearer',
        expires_in: Tokens::ACCESS_TTL, refresh_token: Tokens.issue_refresh(user_id) }.to_json
    end
  end

  post '/login' do
    user = USERS[params[:user]]
    # Real code: compare a bcrypt/argon2 hash, not plain text
    halt_json 401, 'bad credentials' unless user && user[:password] == params[:password]
    tokens_for(user[:id], user[:roles])
  end

  post '/refresh' do
    digest = Digest::SHA256.hexdigest(params[:refresh_token].to_s)
    entry = Tokens::REFRESH.delete(digest)  # one-time use: rotate on every refresh
    halt_json 401, 'invalid refresh token' unless entry && entry[:expires_at] > Time.now
    user = USERS.values.find { |u| u[:id] == entry[:user_id] }
    tokens_for(user[:id], user[:roles])
  end

  post '/logout' do
    Tokens::REVOKED[claims['jti']] = claims['exp']
    status 204
  end

  get '/me' do
    { user_id: claims['sub'], roles: claims['roles'] }.to_json
  end

  get '/admin/stats' do
    halt_json 403, 'admin role required' unless claims['roles'].include?('admin')
    { users: USERS.size }.to_json
  end
end

And a script that drives it with rack-test:

require_relative 'api'
require 'rack/test'

include Rack::Test::Methods
def app = Api

def show(label)
  puts "#{label}: #{last_response.status} #{last_response.body}"
end

get '/me'; show 'no token'

post '/login', user: 'alice', password: 's3cret'
tokens = JSON.parse(last_response.body)
puts "login: #{last_response.status} keys=#{tokens.keys}"
access = tokens['access_token']

header 'Authorization', "Bearer #{access}"
get '/me'; show 'me'
get '/admin/stats'; show 'admin'

forged = JWT.encode({ sub: '1', iss: Tokens::ISSUER, aud: 'api', exp: Time.now.to_i + 60,
                     jti: 'x', roles: ['admin'] }, 'guessed-secret', 'HS256')
header 'Authorization', "Bearer #{forged}"
get '/me'; show 'forged'

post '/login', user: 'bob', password: 'hunter2'
bob = JSON.parse(last_response.body)
header 'Authorization', "Bearer #{bob['access_token']}"
get '/admin/stats'; show 'bob admin'

# Refresh: the old refresh token works exactly once
header 'Authorization', nil
post '/refresh', refresh_token: tokens['refresh_token']
fresh = JSON.parse(last_response.body)
puts "refresh: #{last_response.status} new token differs=#{fresh['access_token'] != access}"
post '/refresh', refresh_token: tokens['refresh_token']; show 'reuse refresh'

# Logout revokes the access token before it expires
header 'Authorization', "Bearer #{fresh['access_token']}"
post '/logout'; puts "logout: #{last_response.status}"
get '/me'; show 'after logout'
puts "www-authenticate: #{last_response.headers['www-authenticate']}"
no token: 401 {"error":"missing bearer token"}
login: 200 keys=["access_token", "token_type", "expires_in", "refresh_token"]
me: 200 {"user_id":"1","roles":["admin"]}
admin: 200 {"users":2}
forged: 401 {"error":"invalid token"}
bob admin: 403 {"error":"admin role required"}
refresh: 200 new token differs=true
reuse refresh: 401 {"error":"invalid refresh token"}
logout: 204
after logout: 401 {"error":"invalid token"}
www-authenticate: Bearer error="invalid_token"

Design notes:

JWTs are often used where a plain session would be simpler and safer. Here's how they compare with the Sessions article's cookie sessions:

Session cookie JWT access token
Revocation delete the server-side record wait for exp, or keep a denylist
Server state session store (or encrypted cookie) none for access tokens
Verified by other services they need the store or the secret yes, with a public key
Readable by the client no (encrypted) yes (only base64)
Sent automatically by the browser yes, so CSRF protection is needed no, the client adds the header

For a classic server-rendered web app, use a session. JWTs make the most sense for APIs used by mobile or SPA clients, for service-to-service calls, and when tokens come from an external identity provider.

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents