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
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 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.