Authentication and Sessions

Video + 11 min read

User
Session never ends
Login server
User database
Plain text passwords
Attacker
Stolen password
Authentication and Sessions
0:00 / 6:24 · Authentication and Sessions
Chapters and transcript

Authentication and Sessions Authentication is how your app checks who a user is. Many breaches start here. A stolen password. Weak password storage. A session that never ends. In this lesson, you will learn to store passwords safely, protect session cookies, add multi-factor authentication, and slow down password guessing.

Do not build it all Authentication has many small details, and each one can go wrong. Before writing your own login system, look for a well-tested option. The authentication built into your framework, such as Django auth. A maintained library, such as Passport for Express or Auth.js for Next.js. Or a hosted identity provider that handles sign-in, resets and MFA. You still need the ideas in this lesson, to configure and review them.

Storing passwords How should you store passwords? Plain text is the worst. If the database leaks, every account is exposed at once. Do not encrypt them either. Encryption can be reversed, and an attacker who steals the key reads them all. General fast hashes such as MD5, SHA-1 and SHA-256 are too quick, even with a salt. The right tool is a password hashing function: Argon2id, a modern choice, or bcrypt.

Storing passwords A hash is a one-way fingerprint of data: easy to compute, but not possible to reverse. Password hashing functions add two features. A salt is a random value added to each password, so two users with the same password get different hashes. A work factor makes the function slow on purpose. Users do not notice a fraction of a second, but billions of guesses become very slow.

Storing passwords Here is bcrypt in Node.js. Twelve is the cost, the work factor. Hash the same password twice, and you get two different strings, because each one has its own random salt. The library stores the salt inside the hash string, so you store that whole string in the database. At login, bcrypt compare checks a typed password and answers true or false.

Storing passwords For password rules, modern guidance favours length over complicated rules. Allow long passwords and passphrases, set a sensible minimum such as eight or more characters, and reject very common or known-leaked passwords. Avoid forcing strange mixes of symbols. They push users towards writing passwords down.

Sessions and cookies After login, the server must remember the user. The user logs in, and the server creates a session: a long, random session ID in a cookie. The browser sends it with every request. But whoever holds that ID is treated as the user. If an attacker steals it, the server accepts them too. So you must protect it.

Sessions and cookies Set three flags on session cookies. HttpOnly: JavaScript cannot read the cookie, which limits the damage of cross-site scripting. Secure: the cookie is only sent over HTTPS. SameSite, set to Lax or Strict: the browser does not send the cookie on most requests started by other websites. That helps against cross-site request forgery, where another site tricks the browser into acting for the user.

Sessions and cookies You can check this yourself on a project you own. Open the browser DevTools, go to the Application or Storage tab, and look at the session cookie. Here, HttpOnly, Secure and SameSite Lax are all set. In Express, you set them in the cookie options, together with a max age, such as thirty minutes.

Sessions and cookies More session rules. Generate session IDs with a secure random generator, never from a user ID, an email or a timestamp. Create a new session ID at login. Keeping the old one allows session fixation. Expire sessions, with an idle timeout and an absolute timeout. Log out properly, by destroying the session on the server. And end sessions after a password change, so a thief is kicked out.

Multi-factor authentication Multi-factor authentication asks for a second proof, so a stolen password alone is not enough. From strongest to weaker. Passkeys and security keys resist phishing, because they only work on the real website. Authenticator apps show a six-digit code that changes every thirty seconds. SMS codes are better than nothing, but SIM swap fraud can let an attacker receive them. Offer MFA to everyone, require it for admins, and give recovery codes.

Slowing down attackers Attackers guess passwords automatically. Brute force means trying many passwords on one account. Credential stuffing means trying username and password pairs leaked from other websites. Defend login, sign-up and password reset with rate limiting, per account and per IP address. After repeated failures, slow down or block for a while, but do not let attackers lock real users out forever.

Slowing down attackers Here is another defence. Whether the email is unknown or the password is wrong, this login shows one message: invalid email or password. Different messages would let attackers find which accounts exist. The forgot password page works the same way, and says: if an account exists, we have sent a reset link.

Slowing down attackers Password reset needs care too. Reset tokens must be long, random and single-use, and short-lived, for example valid for thirty minutes. Store only a hash of the token. Never email users their old password. If you can, you are storing it wrongly. Finally, alert users by email about a new login or a password change, so they can react if it was not them.

Quick check Quick check. You test your app. You log in, copy the session ID, and log out. Then you send a request with the old session ID, and it still works. What is missing? Choose one.

Key takeaways Let us put it together. Use well-tested authentication options. Hash passwords with Argon2id or bcrypt. Set HttpOnly, Secure and SameSite on session cookies. Create a new session at login, expire it, and destroy it at logout. And add MFA, rate limiting and one generic error message. Check your own login code with the checklist below, then answer the quiz.

Authentication is how your application checks who a user is, usually with a password. Many breaches start here: stolen passwords, weak storage and sessions that never end. This lesson covers how to build login features that hold up against real attacks.

Do not build it all yourself

Authentication has many small details, and each one can go wrong. Before writing your own login system, check whether you can use a well-tested option:

  • The authentication features built into your framework, such as Django's auth system
  • A maintained library, such as Passport for Express or Auth.js for Next.js
  • A hosted identity provider that handles sign-in, password resets and MFA for you

Even if you use one of these, you still need to understand the ideas below, because you will configure them and you will review code that uses them.

Storing passwords safely

Never store passwords as plain text. If the database leaks, every account is exposed at once, and because people reuse passwords, their email and wallet accounts may be exposed too.

Do not encrypt passwords either. Encryption can be reversed with a key, and if the attacker steals the key along with the database, all passwords are revealed. Your application never needs to know a user's password. It only needs to check whether a typed password is correct.

The right tool is a password hashing function. A hash is a one-way fingerprint of data: easy to compute, but not possible to reverse. Password hashing functions add two important features:

  • Salt: a random value added to each password before hashing. Two users with the same password get different hashes, so attackers cannot use ready-made tables of hashes.
  • Work factor: the function is deliberately slow. One login takes a fraction of a second, which users do not notice. But an attacker trying billions of guesses is slowed down enormously.

General hashes such as MD5, SHA-1 and SHA-256 are designed to be fast, so they are the wrong choice for passwords, even with a salt. Use Argon2id (a modern choice) or bcrypt (older, very widely supported).

Node.js with the bcrypt package:

const bcrypt = require('bcrypt');

// When the user signs up: 12 is the cost (work factor)
const hash = await bcrypt.hash(password, 12);

// When the user logs in
const ok = await bcrypt.compare(password, user.passwordHash);

Python with the argon2-cffi package:

from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError

ph = PasswordHasher()
hashed = ph.hash(password)        # on sign-up

try:
    ph.verify(hashed, password)   # on login
    login_ok = True
except VerifyMismatchError:
    login_ok = False

Both libraries create and store the salt inside the hash string for you. Store that whole string in the database.

For password rules, modern guidance favours length over complicated rules. Allow long passwords and passphrases, set a sensible minimum such as 8 or more characters, and reject very common or known-leaked passwords. Do not force strange mixes of symbols that push users towards writing passwords down.

Sessions and secure cookies

After login, the server must remember the user. Usually it creates a session: a long, random session ID stored in a cookie. Whoever holds that ID is treated as the user, so you must protect it.

Set these cookie flags on session cookies:

Flag What it does
HttpOnly JavaScript cannot read the cookie, which limits the damage of XSS
Secure The cookie is only sent over HTTPS
SameSite=Lax or Strict The browser does not send the cookie on most requests started by other websites, which helps against cross-site request forgery (CSRF), where another site tricks the browser into acting for the user

In Express:

res.cookie('sid', sessionId, {
  httpOnly: true,
  secure: true,
  sameSite: 'lax',
  maxAge: 30 * 60 * 1000 // 30 minutes, in milliseconds
});

Other session rules:

  • Generate session IDs with a secure random generator. Session libraries do this. Never use a user ID, an email or a timestamp as a session ID.
  • Create a new session ID at login. If you keep the ID from before login, an attacker who planted an ID in the victim's browser can share the session. This attack is called session fixation. In express-session, call req.session.regenerate() after a successful login.
  • Expire sessions. Use an idle timeout (for example, 30 minutes without activity for a banking-style app) and an absolute timeout (for example, log in again after 12 hours), chosen to suit how sensitive the app is.
  • Log out properly. Destroy the session on the server, not only the cookie in the browser.
  • End sessions after a password change, so a thief who had a session is kicked out.

Multi-factor authentication

Multi-factor authentication (MFA) asks for a second proof in addition to the password, such as a code from an authenticator app. A stolen password alone is then not enough.

Common options, from strongest to weaker:

  1. Passkeys and security keys (based on the FIDO2 and WebAuthn standards). These resist phishing because they only work on the real website.
  2. Authenticator apps that show a six-digit code that changes every 30 seconds. This method is called TOTP (time-based one-time password).
  3. SMS codes. Better than nothing, but SIM swap fraud, where an attacker convinces a mobile operator to move a victim's number to a new SIM, can let an attacker receive the code.

Offer MFA to all users, and require it for admin accounts. Give users recovery codes when they turn MFA on, and make sure your account recovery process cannot be used to skip MFA easily.

Slowing down attackers

Attackers guess passwords automatically. Brute force means trying many passwords on one account. Credential stuffing means trying username and password pairs leaked from other websites, hoping people reused them. Defend your login, sign-up and password reset endpoints:

  • Rate limiting: limit attempts per account and per IP address in a time window. For Express, the express-rate-limit package is a common choice. Slow down or temporarily block after repeated failures, but be careful that attackers cannot lock real users out forever.
  • One generic error message: show "Invalid email or password" in both cases. Different messages let attackers find which accounts exist. Apply the same idea to "forgot password" pages: "If an account exists, we have sent a reset link."
  • Safe password reset: reset tokens must be long, random, single-use and short-lived, for example valid for 30 minutes. Store only a hash of the token. Never email the user their old password, because if you can, you are storing it wrongly.
  • Alerts: tell users by email when there is a new login or a password change, so they can react if it was not them.

Review your own login code

Use this checklist on a project you own:

  1. Find where passwords are stored. Are they hashed with Argon2id or bcrypt?
  2. Open your browser's DevTools, go to the Application or Storage tab, and look at your session cookie. Are HttpOnly, Secure and SameSite set?
  3. Log in, note the session ID, log out, then check that the old session ID no longer works.
  4. Type a wrong password ten times quickly. Does anything slow you down?
  5. Compare the error message for an unknown email with the message for a wrong password. Are they the same?

Fix any "no" answers before your next release.

Check your understanding

Answer every question correctly to complete this lesson. If you miss one, try the quiz again.

1. Which is the right way to store user passwords?

2. What does the HttpOnly flag on a session cookie do?

3. A login page shows 'No account with this email' or 'Wrong password' depending on the mistake. What is the problem?

Locked: answer every quiz question above correctly to complete this lesson.

Spotted a mistake or something unclear? Report a mistake