Magic Links and One-Time Codes
What you'll learn: How to implement secure, passwordless authentication flows using email or SMS-based tokens, and the critical security considerations that keep them safe.
The Core Concept
Magic links and one-time codes (OTCs) are passwordless authentication methods where users receive a time-limited, single-use credential via email or SMS. Instead of entering a password, clicking a link or entering a code proves identity by demonstrating access to a trusted communication channel.
Think of it like this: It's similar to a hotel giving you a keycard that only works for your room and expires at checkout time—temporary, specific, and disposable.
Implementation Security Considerations
Token Generation: Use cryptographically secure random generators (not predictable sequences). Tokens should be long enough to resist brute-force attacks—at least 128 bits of entropy for links, 6+ digits for codes.
Token Expiration: Set aggressive time limits. Magic links should expire in 15-30 minutes; OTCs in 5-10 minutes. Expired tokens must be rejected server-side, never trusting client-side checks.
Rate Limiting: Restrict how often users can request tokens (e.g., one per minute) to prevent abuse and spam. Also limit verification attempts to prevent brute-forcing the code.
Preventing Enumeration: Never reveal whether an email/phone exists in your system. Always return the same "check your inbox" message regardless. This prevents attackers from discovering valid accounts.
Single-Use Enforcement: Once a token is used successfully, immediately invalidate it in your session storage. Prevent replay attacks by tracking consumed tokens.
Transport Security: Always send links over HTTPS. For SMS codes, acknowledge that SMS is less secure than email due to SIM-swapping risks—consider it weaker than authenticator apps but acceptable for many contexts.
Key Takeaway: Magic links and one-time codes provide passwordless convenience, but security depends on cryptographically strong tokens, aggressive expiration, strict rate limiting, and careful prevention of user enumeration attacks.