ruby 50 lines · 8 steps

Building signed session tokens in Ruby

A self-contained class that mints and verifies tamper-proof, expiring tokens using an HMAC signature.

Explained by highlit
1require "openssl"
2require "json"
3require "base64"
4 
5class SessionToken
6 class InvalidToken < StandardError; end
7 
8 def self.secret
9 @secret ||= ENV.fetch("SESSION_TOKEN_SECRET")
10 end
11 
12 def self.encode(payload, ttl: 3600)
13 claims = payload.merge(exp: Time.now.to_i + ttl)
14 body = base64(JSON.generate(claims))
15 "#{body}.#{sign(body)}"
16 end
17 
18 def self.decode(token)
19 body, signature = token.to_s.split(".", 2)
20 raise InvalidToken, "malformed token" unless body && signature
21 
22 expected = sign(body)
23 unless OpenSSL::Utils.respond_to?(:secure_compare) ||
24 secure_compare(expected, signature)
25 raise InvalidToken, "signature mismatch"
26 end
27 
28 claims = JSON.parse(Base64.urlsafe_decode64(body), symbolize_names: true)
29 raise InvalidToken, "expired" if claims[:exp] && claims[:exp] < Time.now.to_i
30 
31 claims
32 rescue JSON::ParserError, ArgumentError
33 raise InvalidToken, "undecodable payload"
34 end
35 
36 def self.sign(body)
37 digest = OpenSSL::HMAC.digest("SHA256", secret, body)
38 Base64.urlsafe_encode64(digest, padding: false)
39 end
40 
41 def self.base64(data)
42 Base64.urlsafe_encode64(data, padding: false)
43 end
44 
45 def self.secure_compare(a, b)
46 return false unless a.bytesize == b.bytesize
47 
48 OpenSSL.fixed_length_secure_compare(a, b)
49 end
50end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1An HMAC over the payload lets you detect tampering without encrypting the data itself.
  2. 2Comparing signatures with a constant-time function avoids leaking secrets through timing side channels.
  3. 3Baking an expiry claim into the signed body makes token lifetime tamper-proof rather than trusting the client.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building signed session tokens in Ruby — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code