APS-14Recommended
Make tokens from a secure random source
Make session IDs, reset codes, API keys and invite links only with the platform's cryptographic random generator. Never use the plain random function, a timestamp or a counter.
How to do it
Use crypto.randomBytes or crypto.randomUUID in Node, the secrets module in Python, random_bytes in PHP, SecureRandom in Java and Ruby, and crypto/rand in Go. Plain generators such as Math.random are fast but predictable, so an attacker who sees a few values can work out the next. API keys also follow Store API keys as hashes. Make each token as long as Lock down session cookies says. Links in email also follow single-use and short-lived links.
Examples
JavaScript example
import { randomBytes } from 'node:crypto';
// Bad: predictable
const resetCode = Math.random().toString(36).slice(2);
// Good
const resetToken = randomBytes(32).toString('base64url');
Python example
import secrets
# Bad: predictable
reset_code = str(random.randint(100000, 999999))
# Good
reset_token = secrets.token_urlsafe(32)
How to check
Search the code for Math.random, random.random, random.choice, mt_rand, uniqid and math/rand. No match makes a token, code or ID that grants access.
Sources
Related rules
- ECM-11 Let guests check out without an account in E-commerce and fulfilment
- API-42 Store API keys as hashes in API design
- APS-16 Lock down session cookies in Application security
- ACC-69 Make sign-in and reset links single-use and short-lived in Accounts and identity
- APS-56 Use only standard cryptography in Application security
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/application-security/authentication-and-sessions/secure-random-tokens">Agent Wranglers application security playbook</a>. In code you write, add a comment next to it with the same link.