Square CloudSquare Cloud

Authentication vs authorization: the difference in practice

Authentication confirms who is making the request; authorization decides whether that identity may perform that action on that resource. Without valid credentials an API returns 401; authenticated but not allowed, 403.

Updated 8 min read

Learning objectives

After reading this article you will be able to:

  • Tell authentication from authorization and know where each one runs in an API
  • Use 401, 403 and 404 the way RFC 9110 defines them
  • Avoid the bug of checking only the login, with roles, scopes and ownership checks
On this page

Almost every API has a login route and a set of protected routes. The trouble is that "protected" hides two different questions: who is calling, and whether that caller may do what they asked. Mixing them up is behind one of the most common API flaws: a user signs in with their own account and reads someone else's orders by changing a number in the URL.

This guide separates the two concepts, shows which HTTP status to send for each failure and where each check lives in an Express server, with an example that runs.

What are authentication and authorization?#

Authentication is proving who you are. The client presents a credential (a password, a token, an API key, a certificate, a second factor) and the server checks that it is valid. The result is an identity: "this request comes from user u1".

Authorization is deciding what that identity may do. The OWASP Authorization Cheat Sheet defines it as verifying that a requested action or service is approved for a specific entity, and notes that it is distinct from authentication: an authenticated user is often not allowed to reach every resource or perform every action the system offers.

An office building makes it concrete. At the front desk you show an ID and get a badge: that is authentication. Then the badge opens some doors and not others: that is authorization. A valid badge does not open the finance room just because it is valid.

What are the differences, side by side?#

Authentication Authorization
Question Who are you? What may you do here?
When it runs First, once per request After that, for every action and resource
Input A credential (password, token, key) Identity, action and resource
Result An identity, or none Allowed or denied
Typical failure 401 Unauthorized 403 Forbidden (or 404)
Where it lives Global middleware, login provider Routes, business rules, database queries
Examples Password, JWT, session, OpenID Connect Roles (RBAC), scopes, resource owner

Look at the "When it runs" row. Authentication is the same for every route: the token is valid or it is not. Authorization changes from route to route and from record to record, and that is where the bugs show up.

When do you use 401 and when 403?#

The names are misleading: status 401 is called "Unauthorized", but it is about authentication. RFC 9110, which defines HTTP semantics, splits them like this:

  • 401 Unauthorized: the request was not applied because it lacks valid authentication credentials. A server that sends 401 must send a WWW-Authenticate header with at least one challenge, such as Bearer. The client may retry with a different credential.
  • 403 Forbidden: the server understood the request and refuses to fulfill it. If credentials were sent, it considers them insufficient, and the client should not repeat the request with the same credentials.
  • 404 Not Found instead of 403: the RFC allows a server to answer 404 to hide that a forbidden resource exists.

For APIs that use Bearer tokens, RFC 6750 follows the same line: an invalid or expired token (invalid_token) gets 401, and a valid token without the required scope (insufficient_scope) gets 403.

The working rule: 401 means "I don't know who you are, authenticate"; 403 means "I know who you are, and the answer is no". A 404 fits when the mere existence of the resource is information, such as another customer's order.

Where does each one live in an API?#

In an Express API, authentication is usually a middleware that runs before every protected route. Authorization shows up at two levels: per function (only admins delete orders) and per object (each customer sees only their own orders). The example uses Express 5 and the jose library to verify the JWT:

js
// npm install express@5 jose
import express from "express";
import { jwtVerify } from "jose";

const app = express();
const secret = new TextEncoder().encode(process.env.JWT_SECRET);

// Example data: in production, orders come from the database
const orders = new Map([
  ["o1", { id: "o1", ownerId: "u1", total: 120 }],
  ["o2", { id: "o2", ownerId: "u2", total: 80 }],
]);

// 1. Authentication: who are you?
async function authenticate(req, res, next) {
  const [scheme, token] = (req.get("Authorization") ?? "").split(" ");
  if (scheme !== "Bearer" || !token) {
    res.set("WWW-Authenticate", "Bearer");
    return res.status(401).json({ error: "Sign in first" });
  }
  try {
    const { payload } = await jwtVerify(token, secret, { algorithms: ["HS256"] });
    req.user = { id: payload.sub, role: payload.role };
    next();
  } catch {
    res.set("WWW-Authenticate", 'Bearer error="invalid_token"');
    res.status(401).json({ error: "Invalid or expired token" });
  }
}

// 2. Role-based authorization: what may you do?
function requireRole(...roles) {
  return (req, res, next) => {
    if (!roles.includes(req.user.role)) {
      return res.status(403).json({ error: "Forbidden" });
    }
    next();
  };
}

app.use(authenticate); // every route below requires a login

app.get("/orders/:id", (req, res) => {
  const order = orders.get(req.params.id);
  // 3. Ownership check: is this order yours?
  const canRead = order && (order.ownerId === req.user.id || req.user.role === "admin");
  if (!canRead) return res.status(404).json({ error: "Order not found" });
  res.json(order);
});

app.delete("/orders/:id", requireRole("admin"), (req, res) => {
  orders.delete(req.params.id);
  res.sendStatus(204);
});

app.listen(Number(process.env.PORT) || 3000);

The three layers stay separate:

  1. authenticate reads the token, verifies the signature and expiry, and puts the identity in req.user. No valid token, 401 with WWW-Authenticate.
  2. requireRole("admin") blocks the whole route for anyone without the role. Authenticated without the role, 403.
  3. Inside the handler, order.ownerId === req.user.id decides whether that specific record may be read. Someone else's order gets 404, the same as an order that does not exist.

To test it, issue tokens with the same secret:

js
// node token.js u1 customer
import { SignJWT } from "jose";

const secret = new TextEncoder().encode(process.env.JWT_SECRET);
const [sub = "u1", role = "customer"] = process.argv.slice(2);

const token = await new SignJWT({ role })
  .setProtectedHeader({ alg: "HS256" })
  .setSubject(sub)
  .setIssuedAt()
  .setExpirationTime("15m")
  .sign(secret);

console.log(token);

With the u1 token, GET /orders/o1 returns 200, GET /orders/o2 returns 404 and DELETE /orders/o2 returns 403. With an admin token, all three go through. Without a token, everything returns 401. JWT_SECRET must be long and random (32 bytes or more): RFC 8725 forbids using a human-memorable password as an HS256 key. Keep it in an environment variable, as how to keep secrets out of your code explains. If you are still choosing between tokens and cookies for the login, read JWT vs cookie sessions.

Roles, scopes or resource owner: which model?#

You don't have to pick one. Each model answers part of the question:

  • RBAC (role-based access control): permissions are tied to roles, and each user gets one or more roles. NIST standardized this model, now the INCITS 359 standard. It works well for rules by function, such as "only admin deletes" or "support reads but does not edit".
  • Scopes: limit what a token may do, whoever owns it. In OAuth 2.0 (RFC 6749), the client requests scopes and the server issues a token restricted to them. It is the natural model for API keys and integrations: a key with the orders:read scope deletes nothing, even if it belongs to an admin.
  • Resource owner and attributes: compare the record with the caller. This is what RBAC alone cannot express: every customer has the customer role, but each one may only see their own orders. OWASP recommends attribute-based (ABAC) and relationship-based (ReBAC) models for application development, precisely because they express this kind of rule.

Some rules apply to every model, according to OWASP: deny by default, check permissions on every request (ideally in one central place, such as a middleware), give each user and each key the least privilege it needs, and don't leak details in error messages.

What is the classic mistake?#

Checking only authentication. The route below requires a login, so it looks protected:

js
// Wrong: any authenticated user can read any order
app.get("/orders/:id", authenticate, (req, res) => {
  res.json(orders.get(req.params.id));
});

Changing o1 to o2 in the URL is enough to read someone else's order. The flaw has a name: IDOR (Insecure Direct Object Reference), which OWASP describes as accessing or modifying other people's objects by manipulating the identifier in the URL or parameters, because an access control check is missing. In the OWASP API Security Top 10 2023 it is the first item, API1:2023 Broken Object Level Authorization (BOLA). The fifth item, API5:2023 Broken Function Level Authorization, is the per-function version: a regular user calls an admin route because nobody checked the role. And in the OWASP Top 10:2025, Broken Access Control is still number one.

How to avoid it:

  • Check ownership on every route that takes an ID from the client, including PUT, PATCH and DELETE, not just GET.
  • Filter in the query, not afterwards: WHERE id = $1 AND owner_id = $2 never lets the other user's record leave the database.
  • Don't trust the frontend. Hiding a button does not protect the route; OWASP notes that access control is only effective in trusted server-side code.
  • Random IDs help, but they are not enough. UUIDs are hard to guess, and OWASP treats them as defense in depth: if someone obtains the ID through a shared link or a log, the check still has to block them.
  • Write authorization tests: user A requesting user B's resource must always fail.

Strong authentication matters too. Store passwords with a slow hash (why hashing and not encryption and which algorithm to use), protect the login against brute force and, if the session lives in a cookie, against CSRF. The rest is in the API production checklist.

How to do this on Square Cloud#

On Square Cloud, your API's authentication and authorization stay in your code: the platform hosts the process, and the middleware you wrote decides between 401, 403 and 404. Every published web application gets a *.squareweb.app subdomain with HTTPS on every plan, so the Bearer token and the session cookie travel encrypted. Store JWT_SECRET in the application's environment variables, never in the code: changes apply on the next restart, and one application cannot read another one's variables, even in the same account. The network has a WAF and DDoS mitigation, but a WAF doesn't know who owns order o2: that rule is yours.

Your account follows the same split. Signing in to it takes no password: you get in with a one-time code sent to your email or through OAuth. API keys, created in your account on every plan, have scopes: give each key only what it needs. A key for the AI Gateway (from the Standard plan), for example, uses the ai:chat scope. For teams, there are workspaces from the Standard plan (3 to 7 members; up to 20 on Pro and up to 50 on Enterprise).

See what else goes into API hosting.

Infrastructure

L3/L4/L7 DDoS mitigation and a WAF on every plan

API hosting

FAQs

Which comes first, authentication or authorization?

Authentication. Without knowing who sent the request, there is no way to decide what they may do. Public routes are the exception: they require neither.

What is the difference between 401 and 403?

Return 401 when valid credentials are missing: no token, an expired one or an invalid one. Return 403 when the server knows who you are and still refuses. To avoid revealing that a resource exists, RFC 9110 allows a 404 instead.

Is OAuth authentication or authorization?

OAuth 2.0 is an authorization protocol: it gives an app limited access, through scopes, to a user's resources. Authentication comes from OpenID Connect, an identity layer built on top of OAuth 2.0.

Does hiding a button in the frontend protect the route?

No. Anyone who calls the API directly, with curl or the browser's developer tools, skips the frontend. The permission check has to run on the server, on every request.

Do random IDs (UUIDs) prevent IDOR?

They make IDs hard to guess, but they do not replace the check. OWASP treats unpredictable IDs as defense in depth: if someone obtains the ID of another user's resource, the API still has to refuse.

Next articleJWT vs cookie sessions: which to use for loginWith sessions, state lives on the server and the cookie holds an ID; with JWT, the data travels in the token. Compare logout, CSRF, XSS and multiple instances.

More in Security

See all 24 articles