Authentication Patterns
~290 words ยท 2 min read
Storing passwords
Never store plaintext passwords. Instead, hash them with a slow, salted algorithm designed for passwords:
- bcrypt โ the longtime standard, with a tunable cost factor.
- argon2 โ the modern winner of the Password Hashing Competition; memory-hard to resist GPUs.
Plain SHA-256 is too fast โ attackers can guess billions per second on a GPU. bcrypt and argon2 are deliberately slow.
Session-based auth
- User logs in; the server creates a session and stores it (in memory or a DB).
- The server sends the client a session ID in a cookie.
- On each request, the cookie comes back and the server looks up the session.
State lives on the server; the cookie is just an identifier.
JWT (JSON Web Tokens)
Instead of a session ID, the server hands the client a signed token containing the user's claims. The client sends it on each request, and the server verifies the signature โ no session lookup needed.
JWTs are stateless and scale beautifully, but you can't easily revoke one before it expires โ the server has no record to delete. Use short lifetimes plus a refresh token.
OAuth2
OAuth2 lets a user grant a third-party app limited access to their data on another service โ "Log in with Google" โ without handing over their password. It's about delegated access, not authentication per se.
Other pieces
- API keys โ long-lived secrets for service-to-service calls.
- MFA โ a second factor (app code, SMS, hardware key) so a stolen password alone isn't enough.