appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Authentication, sessions and CSRF

Lesson 2 of 311 minIntermediate

Store passwords correctly, protect sessions and stop forged requests.

Storing passwords

  • Never store passwords in plain text, and never use a fast hash such as MD5 or plain SHA-256 for them.
  • Use a slow, salted password hash: Argon2id, scrypt or bcrypt.
  • Each password gets its own random salt, so identical passwords do not produce identical hashes.
  • Never email a password. Send a time-limited reset link.

Sessions

  • Generate session IDs with a cryptographically secure random generator.
  • Set cookies Secure, HttpOnly and SameSite=Lax or Strict.
  • Issue a new session ID after login to prevent session fixation.
  • Expire sessions and revoke them on logout and password change.

CSRF

Cross-site request forgery makes a victim's browser send a request to your site while logged in, because browsers attach cookies automatically. Defenses:

  • SameSite cookies, which stop most cross-site sends.
  • A secret CSRF token in each state-changing form that the server verifies.
  • Never change data with GET requests.

Authorization

CarefulLogging in is not the same as being allowed. On every request, check that this user may access this record. Skipping that check (insecure direct object references) is one of the most common real-world bugs.

Add rate limiting and lockouts to login endpoints, and offer two-factor authentication.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. Which is suitable for storing passwords?
2. What does a CSRF token prove?
3. After a user logs in, what should you do with the session ID?
4. A logged-in user changes /orders/123 to /orders/124 and sees someone else's order. What is missing?

Key terms