Access Control and APIs

Video + 11 min read

Customer A
API server
What may you do?
Invoices
GET invoice 1041
GET invoice 1042
Customer B invoice
Access Control and APIs
0:00 / 6:33 · Access Control and APIs
Chapters and transcript

Access Control and APIs Logging in answers one question: who are you? The next question is: what are you allowed to do? That is authorisation, and getting it wrong is the most common serious web risk. Here a customer opens their own invoice. Then they change the ID in the request, and a careless server returns an invoice that belongs to someone else. In this lesson, you will learn to build the checks that stop this, and to protect APIs.

Checks on every request Access control means enforcing rules about who can read or change what. Three rules make most of the difference. Check on the server. Hiding a button or a menu does nothing for security. Check on every request. Do not assume a user on page two passed the check on page one. And deny by default. If no rule clearly allows an action, block it.

Checks on every request The delete button is hidden from normal users on the web page. But anyone can call your API directly. Here a normal test user calls the delete product API with curl. The server checks the role on every request, so it answers four oh three, forbidden. Without that server check, the product would be gone.

Checks on every request You usually need two kinds of check. A function-level check asks: is this user allowed to use this feature at all? For example, only admins may delete products. An object-level check asks: is this user allowed to touch this specific record? For example, a customer may view orders, but only their own.

Checks on every request Put function-level checks in one shared place, called middleware: code that runs before your route handlers, so no route can forget the check. A request with no login gets four oh one, which means you are not logged in. A customer gets four oh three: logged in, but not allowed. Only an admin reaches the delete product route.

Preventing IDOR An IDOR, an insecure direct object reference, happens when your code fetches a record by an ID from the request, without checking who owns it. The ID comes from the user, and there is no owner check, so changing the number shows data that belongs to someone else. The Web Hacking path shows how testers find these. As a developer, you make ownership part of every lookup.

Preventing IDOR The bad query finds an invoice by its ID only. The good query also requires the customer ID to match the logged-in user. Take that identity from the session or a verified token, never from a field in the request, such as customer ID equals seventeen. If no row comes back, return four oh four, not found.

Preventing IDOR Test it on your own app. Logged in as test customer B, open your own invoice, then change the ID in the address bar. A fixed server answers four oh four, which does not even confirm the invoice exists. Apply the same check to every action: view, edit, delete, download and export. Developers often protect view and forget download PDF. Random IDs such as UUIDs are an extra layer, not the fix.

Mass assignment Mass assignment happens when your code copies every field from the request into a record. A profile update should only change name and phone. But if a user adds role admin, or a balance of fifty thousand, careless code saves it. The fix is to pick only the fields users may change. Django forms and Pydantic models let you list them. Role, price, balance and status belong to trusted server code.

API keys and tokens An API key is a long secret string that identifies a calling application. Treat it like a password. Keep secret keys on the server, never in front-end JavaScript or a mobile app. Send keys in a header, such as Authorization, not in the URL, because URLs end up in history and logs. Give each key only the permissions it needs, and allow keys to be revoked and rotated. If you issue keys to customers, store only a hash.

API keys and tokens A JSON Web Token, or JWT, is a token holding claims, such as a user ID and an expiry time, plus a signature that proves your server created it. By default it is signed, not encrypted, so anyone holding it can read it. Never put secrets inside. Always verify the signature and the expiry, with a maintained library, and name the algorithm you expect. And keep access tokens short-lived, such as fifteen minutes.

CORS basics Browsers follow the same-origin policy. CORS lets your API tell browsers which other origins may read its responses. A page from your trusted origin can read the response. A page from another website cannot, because the browser blocks it. But only browsers enforce CORS. curl, scripts and other servers ignore it completely. So your API still needs authentication and authorisation on every route.

CORS basics A loose CORS setting can hurt your logged-in users. Use an explicit list of trusted origins, such as app dot chaicorp dot example, with the Express cors package. Avoid code that copies whatever Origin header arrives back into the allow origin header while also allowing cookies. Then a malicious website could read the data of your users through their browsers. Browsers refuse the star wildcard with credentials, which is why developers fall into this shortcut.

Quick check Quick check. Your mobile app hides the export all users button from normal users. In testing, a normal account calls the export route directly and receives the full user list. What is the right fix? Choose one.

Key takeaways Let us put it together. Check permissions on the server, on every request, and deny by default. Add the owner to every lookup, with the user ID from the session. Pick only the fields users may change. Keep API keys on the server, and always verify JWTs. And remember CORS is not access control. Test your own app with two accounts, turn the tests into automated tests, then answer the quiz.

Logging a user in only answers the question "who are you?". The next question, "what are you allowed to do?", is called authorisation, and getting it wrong is the most common serious web risk. This lesson shows how to build the checks into your code, and how to protect APIs that mobile apps and other systems use.

Server-side checks on every request

Access control means enforcing rules about who can read or change what. Three rules make most of the difference:

  1. Check on the server. Hiding a button, a menu item or an admin page in the front end does nothing for security. Anyone can call your API directly.
  2. Check on every request. Each API route must check permission itself. Do not assume that a user who reached page 2 must have passed the check on page 1.
  3. Deny by default. If no rule clearly allows an action, block it.

There are two kinds of check you usually need:

  • Function-level: is this user allowed to use this feature at all? For example, only admins may delete products.
  • Object-level: is this user allowed to touch this specific record? For example, a customer may view an order, but only their own orders.

Put function-level checks in one shared place, such as middleware (code that runs before your route handlers), so that no route can forget it:

function requireRole(role) {
  return (req, res, next) => {
    if (!req.user) return res.status(401).json({ error: 'Login required' });
    if (req.user.role !== role) return res.status(403).json({ error: 'Forbidden' });
    next();
  };
}

app.delete('/api/products/:id', requireRole('admin'), deleteProduct);

Status code 401 means "you are not logged in". 403 means "you are logged in, but you may not do this".

Preventing IDOR in your code

An IDOR (insecure direct object reference) bug happens when your code fetches a record by an ID from the request and never checks who owns it. The Web Hacking path shows how testers find these. As a developer, the fix is to make ownership part of every lookup.

Node.js with mysql2:

// Bad: any logged-in user can read any invoice by changing the ID
const [rows] = await db.execute(
  'SELECT * FROM invoices WHERE id = ?',
  [req.params.id]
);

// Good: the invoice must also belong to the logged-in user
const [rows] = await db.execute(
  'SELECT * FROM invoices WHERE id = ? AND customer_id = ?',
  [req.params.id, req.user.id]
);
if (rows.length === 0) return res.status(404).json({ error: 'Not found' });

Python with sqlite3 follows the same idea:

cur.execute(
    "SELECT * FROM invoices WHERE id = ? AND customer_id = ?",
    (invoice_id, current_user_id),
)

Key points:

  • Take the user's identity from the session or a verified token, never from a field in the request body or URL such as customer_id=17.
  • Returning 404 Not found for records the user does not own is common, because it does not even confirm that the record exists.
  • Apply the check to every action: view, edit, delete, download and export. Developers often protect "view" and forget "download PDF".
  • Random IDs such as UUIDs make guessing harder, but they are an extra layer, not the fix.

Mass assignment

Mass assignment happens when your code copies every field from the request into a database record. If a user adds "role": "admin" or "balance": 50000 to their profile update, the code may save it.

// Bad: copies whatever the client sends
await User.update(req.body, { where: { id: req.user.id } });

// Good: pick only the fields users may change
const { name, phone } = req.body;
await User.update({ name, phone }, { where: { id: req.user.id } });

Python frameworks offer the same protection. For example, Django forms and Pydantic models let you list exactly which fields are accepted. Fields such as role, price, balance and account status should only be changed by trusted server code.

API keys and tokens

APIs often use keys or tokens instead of cookies, especially for mobile apps and system-to-system calls.

An API key is a long secret string that identifies a calling application. Treat it like a password:

  • Keep secret keys on the server. Never put them in front-end JavaScript or inside a mobile app, because users can extract them.
  • Send keys in a header, such as Authorization, not in the URL. URLs are saved in browser history and server logs.
  • Give each key only the permissions it needs, and allow keys to be revoked and rotated (replaced with new ones).
  • If you issue keys to your own customers, store only a hash of each key, just like passwords.

A JSON Web Token (JWT) is a common type of token. It contains claims, such as a user ID and an expiry time, plus a signature that proves the server created it. Important facts:

  • A JWT is signed, not encrypted by default. Anyone holding it can decode and read its contents, so never put secrets or private data in it.
  • Always verify the signature and the expiry before trusting a token. Use a maintained library and tell it which algorithm you expect:
const jwt = require('jsonwebtoken');

const claims = jwt.verify(token, process.env.JWT_SECRET, {
  algorithms: ['HS256']
});
  • Keep access tokens short-lived, such as 15 minutes, so a stolen token stops working soon.

CORS basics

Browsers follow the same-origin policy: a script on one website cannot read responses from another website. An origin is the combination of scheme, host and port, such as https://app.chaicorp.example.

CORS (Cross-Origin Resource Sharing) lets your API tell browsers which other origins may read its responses, using headers such as Access-Control-Allow-Origin.

Two things beginners often misunderstand:

  1. CORS is not access control for your API. Only browsers enforce it. Tools like curl, scripts and other servers ignore it completely. Your API still needs authentication and authorisation on every route.
  2. A loose CORS setting can hurt your logged-in users. If your API trusts any origin and also allows cookies, a malicious website could read your users' data through their browsers.

Use an explicit list of trusted origins. With the Express cors package:

const cors = require('cors');

app.use(cors({
  origin: ['https://app.chaicorp.example'],
  credentials: true
}));

Avoid code that copies whatever Origin header arrives back into Access-Control-Allow-Origin while also allowing credentials. Browsers already refuse the wildcard * together with credentials, which is one reason developers fall into this shortcut.

Test your own access control

On an application you own, create two normal test accounts, A and B, plus one admin account. Then:

  1. Log in as A and note the IDs of A's records in DevTools, in the Network tab.
  2. Log in as B and request A's records by ID. You should get 403 or 404.
  3. As a normal user, call an admin-only API route directly. It should be refused.
  4. Send a profile update with an extra field such as role. It should be ignored.
  5. Turn these steps into automated tests, so a future change cannot quietly break them.

Check your understanding

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

1. A route loads an order with SELECT * FROM orders WHERE id = ?. Users must only see their own orders. What is the best fix?

2. What is true about CORS?

3. Where should an API key for your payment provider be kept?

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

Spotted a mistake or something unclear? Report a mistake