Authentication, sessions and CSRF
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,HttpOnlyandSameSite=LaxorStrict. - 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:
SameSitecookies, which stop most cross-site sends.- A secret CSRF token in each state-changing form that the server verifies.
- Never change data with
GETrequests.
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.