API Security (CORS, CSRF, Input Sanitization)

Check seven things: HTTPS only (encrypted HTTP) plus the HSTS header (the browser always uses HTTPS); auth (the token check) on every route; object-level…

Out of curiosity, Budi changes the order number in his request, from GET /orders/1 to GET /orders/2. The screen right away shows Siti's order, with her home address. Budi hacked nothing. His token is valid, and the server simply forgot to check one thing: who order number 2 belongs to.

This is about API security, which isn't one feature but a checklist. Every way in must be locked, because an attacker only needs to find the one way in that was forgotten. It's like an office building's guard with a checklist. Everyone comes in through the guarded front door. Every visitor shows an ID card. A visitor may only go to the floor they're visiting, not to every room. Their bags are checked. Someone trying to get in 100 times a minute is stopped. When the alarm goes off, the guard doesn't read the building's floor plan over the loudspeaker. And parcels are only handed to couriers on the list.

The Bookshop API checklist

Seven checks, in the same order as the guard's habits above, each with a sample request and the safe answer:

# Check Sample request The safe answer
1 HTTPS only GET http://api.bookshop.test/orders/1 refused with no data; HTTPS answers carry Strict-Transport-Security
2 Auth on every route DELETE /books/1 with no token 401 Unauthorized
3 Object-level authorization Budi: GET /orders/2 (Siti's) 404 Not Found
4 Input validation POST /books with "price": -5000 422
5 A rate limit on login 10 POST /login calls with a wrong password 429 from the 6th attempt
6 No stack traces GET /books/abc, which triggers a bug 500 with {"error": "Internal Server Error"} only
7 CORS with an allowlist GET /orders from a page on https://evil.test no Access-Control-Allow-Origin: https://evil.test

Object-level authorization

A token proves who is calling (authentication). But it doesn't yet answer whether that person may read the object they asked for, such as one order (authorization). A server that only checks the token hands Siti's home address to Budi. This problem is number 1 in the OWASP API Security Top 10 2023, a list of the most serious API risks: Broken Object Level Authorization.

The route below checks the token and the order's owner:

app.get("/orders/:id", requireAuth, (req, res) => {
  const order = orders.find((o) => o.id === Number(req.params.id));
  if (!order || order.user_id !== req.user.id) {
    return res.status(404).json({ error: "Order not found" });
  }
  res.json(order);
});

So the right answer for Budi is 404 (or 403), not Siti's order.

CORS: the list of allowed origins

An origin is where a web page comes from: the protocol, host and port (the number after the host, if any) in its URL, such as https://bookshop.test. By default, a browser blocks a page from another origin from reading your API's answers, unless the server allows it through the Access-Control-Allow-Origin header. This rule is called CORS (Cross-Origin Resource Sharing).

The cors middleware below allows only the Bookshop website:

app.use(cors({
  origin: ["https://bookshop.test"], // an allowlist, not every origin
  credentials: true,
}));

credentials: true allows requests that carry a login cookie (credentials).

The mistake: reflecting any origin (origin: true) while allowing credentials. Reflecting means the server copies the caller's origin into Access-Control-Allow-Origin, so every origin is allowed. A page on https://evil.test opened by a logged-in user can then read that user's orders. This happens when the API uses a login cookie that is sent across sites (SameSite=None). A Bearer token is not sent automatically like a cookie, but keep the allowlist anyway. CORS only limits browsers. curl or another server can still call your API, so CORS is no replacement for auth.

CORS stops another site from reading an answer, but not from sending a request. An attack that uses this gap is called CSRF (Cross-Site Request Forgery): another site sends a forged request in the user's name. For example, a page on https://evil.test submits a form to POST /orders, and the browser attaches the user's login cookie by itself. The Bookshop API reads its token from the Authorization header, which the browser never adds by itself. So CSRF can't use that token. An API that logs in with a cookie needs two locks. First, SameSite=Lax on the cookie, so that cookie isn't sent along with a POST form from another site. Second, a CSRF token: a code that every request that changes data must send back. In Laravel Sanctum, that CSRF token is in the XSRF-TOKEN cookie, and it is sent back as the X-XSRF-TOKEN header.

Input: validate, then query with parameters

Everything that comes from the client is checked first: type, range, length. A price of -5000 is refused with 422. Then, never paste input into the text of a query. Here are two ways to send an id from the client into an SQL query (the table u holds the users):

// SQL injection: input pasted straight into the query
db.query(`SELECT * FROM u WHERE id = ${req.body.id}`);

// safe: a parameterized query, the value sent separately
db.query("SELECT * FROM u WHERE id = ?", [req.body.id]);

If req.body.id holds 1 OR 1=1, the first version returns every user, because 1=1 is always true. The second version, a parameterized query, sends the value separately through the ? placeholder, so 1 OR 1=1 is treated as a single value.

In the exercise, you build a simple cleaner for a plain-text field (text with no HTML):

function sanitizeInput(input) {
  const withoutTags = String(input).replace(/<[^>]*>/g, "");
  const trimmed = withoutTags.trim();
  return trimmed === "" ? null : trimmed;
}

These are the results of sanitizeInput for five inputs:

Input Result
"<script>alert(1)</script>hello" alert(1)hello
"O'Brien" O'Brien
" <b>bold</b> " bold
"<p></p>" null
"plain text" plain text

A cleaner like this is only an extra layer. The main defence is still two things: a parameterized query for SQL, and escaping on output for XSS. Escaping means a tag is shown as text, not run. React does it for you.

Errors without stack traces, and helmet

This error handler (from the Error Handling lesson) answers every unexpected error:

app.use((err, req, res, next) => {
  console.error(err); // the details stay in the server log
  res.status(500).json({ error: "Internal Server Error" });
});

A stack trace in an answer leaks file names, library versions and query text to an attacker. So keep the details in the log, and send the client a general message.

For security headers (headers that turn on protections in the browser), Express has the helmet middleware. Write app.use(helmet()) once, and it sets a dozen security headers at the same time, including Strict-Transport-Security, X-Content-Type-Options: nosniff, X-Frame-Options and Content-Security-Policy. It also removes X-Powered-By (a header that names your server's framework).

🤔 How the attacks work

This lesson is a checklist for the defending side. How each attack works is covered in the Security track: "SQL Injection Prevention", "XSS Prevention & Sanitization", "CORS Deep Dive", "CSRF (Cross-Site Request Forgery)", "API Authentication Patterns", "Rate Limiting & Throttling" and "Complete Security Headers".

⚠️ Doors people forget to lock

TL;DR: Check seven things: HTTPS only (encrypted HTTP) plus the HSTS header (the browser always uses HTTPS); auth (the token check) on every route; object-level authorization (a valid token doesn't mean it may read someone else's order: answer 404); input validation (422); a rate limit on login (429); a 500 with no stack trace; and CORS with an allowlist of origins rather than allowing every origin. CORS is a browser rule: a page from another origin (where a page comes from) can't read your API's answers unless the server sends Access-Control-Allow-Origin for that origin. Input pasted into the text of a query is SQL injection; use a parameterized query, which sends the value separately. The helmet middleware sets many security headers with one line.

⚡ Security is a checklist

Meaning: API security is a checklist: every way in must be locked, because an attacker only needs to find the one that was forgotten. The list: HTTPS only (encrypted HTTP), auth (the token check) on every route, object-level authorization (an order only for its owner), input validation, a rate limit on login, errors with no stack trace, and CORS with an allowlist (the list of allowed sites).

⚡ A valid token doesn't mean it may

Write:

app.get("/orders/:id", requireAuth, (req, res) => {
  const order = orders.find((o) => o.id === Number(req.params.id));
  if (!order || order.user_id !== req.user.id) {
    return res.status(404).json({ error: "Order not found" });
  }
  res.json(order);
});
Guess first: Budi has a valid token. He sends GET /orders/2, but order 2 is Siti's. What does a server that only checks the token answer?

Siti's order, with her home address. A token proves who is calling, not that they may read that order.

Meaning: requireAuth makes sure there's a logged-in user, and that user is available in req.user. order.user_id !== req.user.id makes sure the order belongs to that user. Someone else's order gets 404, the same as an order that really doesn't exist, so Budi can't guess which numbers belong to other people's orders.

⚡ CORS with an allowlist

Meaning: An origin is where a web page comes from, such as https://evil.test. A browser blocks a page from another origin from reading your API's answers, unless the server allows it through Access-Control-Allow-Origin. This rule is called CORS. Write an allowlist, the list of allowed origins, and don't allow every origin. CORS only limits browsers, not other programs, so it's no replacement for auth.

⚡ Input: validate, then query with parameters

Meaning: If req.body.id (the id the client sent) holds 1 OR 1=1 and is pasted straight into the query text, the query returns every user, because 1=1 is always true. With a parameterized query (WHERE id = ?), the value is sent separately, so it's treated as a single value.

What you will learn