Authentication — API

Authentication answers "who sent this request?". The client logs in once and gets a token (a proof of identity from the server). Then, on every request, the…

You log in to a shopping app once, then for weeks nobody asks for your password again. Each time the app asks the server for data, what it sends isn't your password but a token: a proof of identity the server gave you when you logged in.

The Bookshop API needs the same thing. Until now anyone could call every one of its endpoints. Yet GET /profile has to know who you are, and DELETE /books/3 is for admins only. Authentication answers one question: who sent this request? It works like a concert wristband. At the ticket booth you show your ID card once, and you get a wristband. That is logging in. After that, at every area you only show the wristband, and the guard doesn't ask for your ID again. The wristband is the token, and the guard is the server. A fake wristband, or one past its date, is refused at the door. A real festival-class wristband used to enter the VIP area is refused too, but for a different reason.

A token in the Authorization header

  1. The client logs in once: POST /auth/login with an email and a password. The server checks the email and password (storing and matching passwords is in the Password Hashing lesson of the Auth track), then answers with a token.
  2. On every later request, the client sends that token in the Authorization header:
GET /profile HTTP/1.1
Host: api.bookshop.test
Authorization: Bearer valid-token-123

The requireAuth middleware

The token check goes into a middleware: a function that runs before the handler. A middleware may pass the request on to the handler, or stop it with its own answer. Here is the requireAuth middleware and the endpoint it guards:

function requireAuth(req, res, next) {
  const header = req.headers.authorization || "";
  const [scheme, token] = header.split(" ");
  if (scheme !== "Bearer" || token !== "valid-token-123") {
    res.set("WWW-Authenticate", 'Bearer realm="bookshop"');
    return res.status(401).json({ error: "Unauthorized" });
  }
  next();
}

app.get("/profile", requireAuth, (req, res) => {
  res.json({ name: "Budi", role: "admin" });
});

The answer requireAuth gives for each header value:

Authorization header Answer
(not sent) 401
Bearer wrong 401
valid-token-123 (no Bearer) 401
Bearer valid-token-123 200

401 or 403

With the concert wristbands, a fake or expired wristband is a 401, and a festival wristband at the VIP door is a 403.

Take Siti. She logged in correctly and holds a valid token, but her role is customer. She sends DELETE /books/3, which is for admins only. The server already knows her from her token, so the answer isn't a 401. She just isn't allowed to delete books: 403.

Who GET /profile DELETE /books/3
No token 401 401
Siti, customer 200 403
Budi, admin 200 204

Checking a role (who may do what) is called authorization. How it differs from authentication is in the Authentication vs Authorization lesson of the Auth track.

Signed tokens

valid-token-123 is easy to guess. Real tokens come in two kinds: a long random string matched against the database, or a signed token (one the server has put a signature on). An example of the second kind is a JWT (JSON Web Token). A JWT has three parts separated by dots: header.payload.signature. The header here isn't an HTTP header: it says how the token was signed.

The server checks a JWT with a function like this:

const crypto = require("crypto");

function verify(token, secret) {
  const [header, payload, signature] = token.split(".");
  const expected = crypto.createHmac("sha256", secret).update(header + "." + payload).digest("base64url");
  if (signature !== expected) return null; // changed, or not made by this server
  const data = JSON.parse(Buffer.from(payload, "base64url").toString());
  if (data.exp * 1000 < Date.now()) return null; // expired
  return data;
}

exp holds seconds, but Date.now() counts in milliseconds. That is why exp is multiplied by 1000.

Say Siti changes "role":"customer" to "role":"admin" in her token's payload. The server calculates the signature again from that payload and gets 5OH8fk4V..., but the token carries lA5MLcmZ.... They don't match, so the answer is 401. In a real app, use a library (for example jsonwebtoken or jose), keep the secret in an environment variable (a setting stored outside the code), and compare signatures with crypto.timingSafeEqual. The details are in the JSON Web Token (JWT) lesson of the Auth track.

API key or user token

How an API key differs from a user token:

User token API key
Stands for one person who logged in one app or server
Comes from POST /auth/login made in a dashboard
Lifetime short (minutes to days) long, until revoked
Sent with Authorization: Bearer ... Authorization: Bearer ... or X-API-Key: ...
Example the buyer's phone app the warehouse syncing stock every night

The server stores an API key as a hash (a one-way scramble that can't be turned back into the key), like a password. So a leaked database doesn't leak the keys with it.

Other options for logging in. This lesson uses a Bearer token in a header, because it works for every kind of client: phone apps, websites and other servers. There are other options:

Way When to pick it
httpOnly session cookie Your own web frontend, on the same domain. The browser keeps a login cookie (a small piece of data) that JavaScript can't read. The browser sends the cookie by itself, so you need CSRF protection (against other sites that make your browser use your cookie). The Password Hashing & Sessions lesson in the PHP track uses this way.
Random token stored in the database Tokens must be revocable at any time, for example on logout or when a phone is lost: delete the row and the token stops working right away. Laravel Sanctum (Laravel's authentication package) works like this.
JWT Many servers need to check a token without asking the database. The drawback: a JWT stays valid until exp, so keep its lifetime short (for example 15 minutes), and use a refresh token (a second token that lives longer) to get a new JWT.
OAuth ("Sign in with Google") Users do not want to create another password. Google checks who they are, then your app still creates its own session or token.

⚠️ Tokens that leak easily, statuses that get swapped

TL;DR: Authentication answers "who sent this request?". The client logs in once and gets a token (a proof of identity from the server). Then, on every request, the client sends that token in the Authorization header with the Bearer ("carrier") scheme: Authorization: Bearer <token>. A requireAuth middleware (a function that runs before the handler) reads req.headers.authorization. When the token is valid, it calls next() to pass the request on. When the token is missing, wrong or expired, it answers 401 with {"error": "Unauthorized"} plus a WWW-Authenticate header (how to log in). Recognised but not allowed, like a customer trying to delete a book: 403. A signed token (JWT) has a payload (the user's data) anyone can read, and an HMAC-SHA256 signature, calculated from the payload, that only the holder of the secret (the server's secret key) can make. So a changed payload is caught. API keys are for apps, tokens for users. Don't keep a token in localStorage (browser storage that is vulnerable to XSS, an attack through a malicious script) and don't send it in a query string.

⚡ The token goes in the Authorization header

Meaning: The client logs in once and gets a token, a proof of identity from the server. Then the client sends that token with every request in the Authorization header with the Bearer scheme ("carrier": whoever carries the token is taken to be its owner): Authorization: Bearer <token>. Without Bearer or its space, the request is refused with 401: the server doesn't know who you are.

⚡ The requireAuth middleware

Write:

function requireAuth(req, res, next) {
  const header = req.headers.authorization || "";
  const [scheme, token] = header.split(" ");
  if (scheme !== "Bearer" || token !== "valid-token-123") {
    res.set("WWW-Authenticate", 'Bearer realm="bookshop"');
    return res.status(401).json({ error: "Unauthorized" });
  }
  next();
}

Meaning: requireAuth is a middleware, a function that runs before the handler. A missing token and a wrong token are both answered 401, with a WWW-Authenticate header that names how to log in. next() passes the request on to the handler. Without next(), the request hangs.

⚡ 401 or 403

Guess first: Siti logs in with a valid token, but her role is customer. She sends DELETE /books/3, which is for admins only. 401 or 403?

It's 403. The server already knows her from her token. She just isn't allowed to delete books.

Meaning: 401 means the server doesn't know who you are. 403 means it knows, but you may not do that.

⚡ Don't keep the token in localStorage

Meaning: localStorage is storage in the browser. localStorage.setItem("token", jwtToken) can be read by any script on the page, so it's vulnerable to XSS (an attack through a malicious script slipped into the page): one malicious script is enough to steal the token. An httpOnly cookie can't be read by JavaScript.

What you will learn