Security

Issue and Use API Tokens Safely

Issue, use, and revoke Bearer API tokens the safe way: store only the SHA-256 digest (never the plaintext), authenticate by digest lookup, separate 401 from 403, revoke with a timestamp, mint tokens from a console/rake command, audit issuance, and rate-limit the endpoint.

Premium

The mental model: the token is a password you never store

An API token is a bearer credential: whoever holds it is the caller. That
makes it exactly as sensitive as a password — and you should treat it like
one. The single most important rule in this playbook is:

Never store the token in plaintext. Store only its digest (a
SHA-256 hash). The plaintext exists for one instant — at issuance — where
you show it once and then forget it. It is never logged and never
re-displayable.

Why a digest and not the raw token? If your database leaks, an attacker with
the raw tokens can call your API immediately. With only digests, they have
hashes that can't be reversed into working tokens. This is the same reasoning
behind hashing passwords — a token is just a machine's password.

A good token has a recognizable prefix so it's easy to spot in logs,
secret scanners, and support tickets, followed by enough random entropy to be
unguessable:

dare_9f2c1a7b4e08d3...   ← prefix "dare_" + long random hex
└──┘ └──────────────┘
tag       secret

The lifecycle you'll build here:

issue  → show plaintext ONCE, store only digest
use    → client sends Authorization: Bearer <token>
         server hashes it, looks up the active key by digest
authz  → authenticate (who?) AND authorize (allowed?) → 401 vs 403
revoke → set revoked_at; authenticate() returns nil forever after

This playbook is concept-first and stack-agnostic. Examples use pseudocode
and HTTP; translate them to your language's hashing library, ORM, and web
framework.

Steps

Subscriber-only content. View plans