Skip to article content
FrontendXLesson 20 / 24

Authentication and sessions for APIs

Build a Node HTTP API from scratch, model data in SQL and MongoDB, and reason about transactions, indexes, caching and authentication so the endpoint you ship stays correct under load.

intermediate · about 55 minutes · 2 exercises

  • Predict
  • Debug

What you will be able to do

#
  • Hash passwords with a slow, salted algorithm.
  • Compare session cookies and signed tokens.
  • Set cookie flags that resist theft and CSRF.

Overview

#

Authentication proves who the caller is. Store passwords only as slow hashes, and carry proof of login either in a server session referenced by a cookie or in a signed token.

Password hashing

Use bcrypt, scrypt or argon2 with a per-password salt and a cost that takes a deliberate fraction of a second. Never store or log the plaintext.

snippet.js
const bcrypt = require('bcrypt');
const hash = await bcrypt.hash(password, 12);
const ok = await bcrypt.compare(candidate, hash);

Sessions versus tokens

A session stores state on the server and gives the client an opaque cookie id; revoking is immediate. A JWT is self-contained and stateless, so in its pure form it cannot be revoked before it expires; keep its lifetime short and pair it with a refresh token. Adding a server-side denylist allows revocation at the cost of reintroducing shared state.

Cookie flags

  • HttpOnly blocks JavaScript access, limiting XSS token theft.
  • Secure sends the cookie only over HTTPS.
  • SameSite=Lax or Strict mitigates CSRF.
  • Path and Max-Age bound scope and lifetime.

Common pitfalls

  • Hashing with fast algorithms like MD5 or SHA-256, which are cheap to brute force.
  • Storing a JWT in localStorage where XSS can read it.
  • Omitting SameSite and shipping a CSRF-able cookie.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Debug

    This code stores passwords in a way that is trivially reversible. Fix it.

    starter.javascript
    const hash = crypto.createHash('sha256').update(password).digest('hex');
    await db.query('INSERT INTO users (email, password) VALUES ($1, $2)', [email, hash]);

    Reveal the reference answer
    reference.javascript
    const bcrypt = require('bcrypt');
    const hash = await bcrypt.hash(password, 12);
    await db.query('INSERT INTO users (email, password_hash) VALUES ($1, $2)', [email, hash]);

    Authored expected output: Passwords stored as a slow bcrypt hash with a per-password salt.

    SHA-256 is fast, so an attacker can test billions of guesses per second. bcrypt with a cost factor is deliberately slow and salts each hash.

  2. Exercise 2Predict

    A session cookie is set without HttpOnly. What class of attack can now read it?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.txt
    Set-Cookie: sid=abc123; Secure; SameSite=Lax
    Choose the best answer

Common misconceptions

#
  • Encrypting passwords is enough: hashing is required, because encryption is reversible.
  • JWTs are more secure than sessions: both are sound; JWTs trade revocability for statelessness.

Follow-up practice

#
  • backend-databases-authorization

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.