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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1An HMAC over the payload lets you detect tampering without encrypting the data itself.
- 2Comparing signatures with a constant-time function avoids leaking secrets through timing side channels.
- 3Baking an expiry claim into the signed body makes token lifetime tamper-proof rather than trusting the client.
Related explainers
ruby
class TasksController < ApplicationController before_action :set_project def reorder
Bulk task reordering with upsert_all in Rails
bulk-update
upsert
authorization
Intermediate
8 steps
javascript
const express = require('express'); const jwt = require('jsonwebtoken'); const crypto = require('crypto');
Refresh token rotation in Express
jwt
token-rotation
authentication
Advanced
9 steps
ruby
class Product < ApplicationRecord belongs_to :category, touch: true has_many :reviews, dependent: :destroy
How Rails models wire up associations
active record
associations
validations
Intermediate
7 steps
ruby
require "net/http" require "json" require "uri" require "base64"
Paginating an HTTP API with a Ruby enumerator
pagination
http
enumerator
Intermediate
7 steps
ruby
class DateRangeMerger def initialize(ranges) @ranges = ranges end
Merging overlapping date ranges in Ruby
sorting
interval-merging
enumerable
Intermediate
5 steps
go
package admin import ( "net/http"
Building a protected admin area in Gin
routing
middleware
authentication
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-signed-session-tokens-in-ruby-explained-ruby-ec53/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.