stackademic

The leading education platform for anyone with an interest in software development.

Authentication Basics

How to verify user identity and store credentials safely

Overview

Authentication is how your app confirms that users are who they claim to be, usually with a password plus an optional second factor. The most common failures are storing passwords insecurely and leaking session tokens. Getting authentication right protects every account on your platform, so it deserves careful attention.

Syntax / Usage

Never store plaintext passwords. Hash them with a slow, salted algorithm such as bcrypt, scrypt, or Argon2 so stolen databases are hard to crack.

import bcrypt from "bcrypt";

// On sign-up: hash before storing
async function register(email, password) {
  const hash = await bcrypt.hash(password, 12); // cost factor 12
  await db.users.insert({ email, passwordHash: hash });
}

// On login: compare with the stored hash (constant-time)
async function login(email, password) {
  const user = await db.users.findByEmail(email);
  if (!user) return null; // avoid revealing which part failed
  const ok = await bcrypt.compare(password, user.passwordHash);
  return ok ? user : null;
}

Examples

Set session cookies with security flags so tokens cannot be stolen easily:

res.cookie("session", token, {
  httpOnly: true, // not readable by JavaScript (limits XSS impact)
  secure: true,   // only sent over HTTPS
  sameSite: "lax", // reduces CSRF exposure
  maxAge: 1000 * 60 * 60,
});

Use a generic error message so attackers cannot enumerate valid accounts:

if (!user) return res.status(401).json({ error: "Invalid credentials" });

Common Mistakes

  • Storing passwords in plaintext or with fast hashes like MD5/SHA-1
  • Forgetting a per-user salt, allowing rainbow-table attacks
  • Leaving session cookies without httpOnly, secure, or sameSite flags
  • Revealing whether the email or the password was wrong on login
  • Not enforcing rate limiting, enabling brute-force guessing

See Also

web-security-fundamentals web-security-https-tls web-security-csrf