Secure Magic Links: Never Store the Raw Token
Magic links appear deceptively simple on the surface: generate a token, place it in a URL, and email it to the user.
However, one fundamental architectural decision determines whether this mechanism is secure: never store the raw token in your database. Treat it with the same security posture as a user's password.
The Hash-at-Rest Authentication Flow
A hardened magic link workflow follows an explicit verification lifecycle:
- Generate a cryptographically secure random token with sufficient entropy.
- Send the raw token to the user exactly once inside the magic link URL.
- Hash the token before persisting any record to the database.
- Persist only the cryptographic hash, accompanied by expiration timestamps, purpose, and consumed state.
- Verify incoming requests by hashing the token provided in the URL and looking up the matching hash in constant time.
- Consume the token atomically within a single transaction, invalidating it immediately while issuing a session or access grant.
Eliminating Bearer Credentials from Leaked Databases
The core security invariant achieved by this pattern is straightforward:
The database must never contain enough information to reconstruct a valid authentication link.
If a database backup or replica is compromised, an attacker cannot extract active tokens to impersonate users. Raw magic-link tokens never exist at rest.
Production Hardening Checklist
Beyond hashing, several defense-in-depth principles are necessary for production magic link systems:
- Short expiration windows: Restrict token validity to 10–15 minutes.
- Strict single-use enforcement: Invalidate the token the moment it is submitted.
- Purpose-bound tokens: Tag tokens explicitly with their intended scope (such as login, email verification, or password reset) so they cannot be repurposed.
- Rate limiting: Apply limits on both token issuance and token verification endpoints to prevent brute-force abuse.
- Atomic consumption: Use database locks or conditional updates to prevent race conditions from concurrent clicks.
- Zero token logging: Ensure reverse proxies, application loggers, and tracing tools scrub the token from URLs and query parameters.
The Authentication Lifecycle
The guiding lifecycle for passwordless links is:
Generate → Send raw → Store hash → Verify → Consume → Expire
Magic links remove passwords from the user experience, but they do not eliminate the responsibility of handling credentials securely. Convenience should never transform an authentication link into a reusable bearer credential.