ruby 8 lines · 1 tab

Secure random token generation for sessions and recovery flows

Kai Nakamura Apr 2026
1 tab
raw_token = SecureRandom.urlsafe_base64(32)
token_digest = Digest::SHA256.hexdigest(raw_token)

PasswordReset.create!(
  user: user,
  token_digest: token_digest,
  expires_at: 30.minutes.from_now,
)
1 file · ruby Explain with highlit

Predictable tokens become account compromise. I use cryptographically secure randomness, store only token digests when possible, and keep token purpose and expiry specific. Reset tokens, magic links, and API secrets should all be treated like credentials, not convenience strings.

Share this code

Here's the card — post it anywhere.

Secure random token generation for sessions and recovery flows — share card
Link copied