# Roles and Ownership: 401 or 403

Signed in isn't the same as allowed, so a requireRole middleware lets only the right role through, an ownership check compares a record's owner with req.user.id, and both refuse with 403, while 401 stays for a request with no valid token.

Journeyman · Node.js · REST API · Updated November 19, 2026

By Gregor Dzierzon

## After this lesson you can

- Write a requireRole middleware that answers 403 when the signed-in user's role isn't allowed
- Check ownership with req.user.id, never with an id the request sends, so users change only their own records
- Choose 401 or 403 for a request the API refuses, reading each as a sentence

## Key takeaways

- A role, such as member or admin, says what kind of user someone is. Sign-in puts it in the signed token, so a caller can't change it.
- requireRole("admin") makes a middleware that answers 403 for any other role. It goes after requireUser, which sets req.user.
- An ownership check compares the record's owner with req.user.id, which came from the signed token. An id in the body is whatever the caller typed.
- 401 is "I don't know who you are; sign in first." 403 is "I know who you are, and you're not allowed", so signing in again won't help.
- Test each rule as each kind of user it treats differently, and once with no token at all.

Almost every app has people who may do more than others. On a forum, you edit your own posts and a moderator removes anyone's. In a shop, staff change prices and customers can't. The API is where those rules are kept, because a hidden button in an app stops nobody who sends the request by hand.

Crew Board's task routes all have requireUser now, from *Requiring a Signed-In User*. The team's rules are that members change only their own tasks, and only an admin, Maya, deletes. But signed in is all requireUser checks. Theo, a member, signs in and deletes Sofia's task:

```http
DELETE http://localhost:3100/tasks/3
Authorization: Bearer <Theo's token>
```

```text
HTTP/1.1 204 No Content
```

Gone. His token was real, so requireUser let him through, and nothing asked whether he was allowed.

## Signed in isn't the same as allowed

Back at the concert hall, Theo's ticket got him into the building. Now he's at the staff room door, and different doors check different things. Crew Board needs two kinds of check:

- **A role**: what kind of user someone is. Crew Board has two, `member` and `admin`, and only admins delete tasks. Giving permissions by role is called **role-based access control**.
- **Ownership**: whose thing it is. Theo and Sofia are both members, yet Theo may change his own tasks and not hers.

Both are authorization, and when either one says no, the answer is `403 Forbidden`.

## Roles, with requireRole

A role belongs to the user, beside their name and password hash, and sign-in copies it into the token:

```javascript
const token = jwt.sign(
  { sub: user.id, name: user.name, role: user.role },
  process.env.JWT_SECRET,
  { expiresIn: "1h" },
);
```

The token is signed, so Theo can't change `member` to `admin`: the forged token in *Requiring a Signed-In User* failed `jwt.verify`. requireUser copies the role into `req.user.role`, and a second middleware checks it:

```javascript
export function requireRole(role) {
  return (req, res, next) => {
    if (req.user.role !== role) {
      return sendProblem(res, 403, `You need the ${role} role for that.`);
    }
    next();
  };
}
```

`requireRole` isn't a middleware itself: it's a function that makes one. Think of a stamp maker: give it the word "admin", and it hands back a stamp that checks for admin. `requireRole("admin")` runs once, when the app starts, and Express calls the middleware it gives back on every request:

```javascript
app.delete("/tasks/:id", requireUser, requireRole("admin"), (req, res) => {
  tasks = tasks.filter((t) => t.id !== Number(req.params.id));
  res.status(204).end();
});
```

Order matters: requireRole reads `req.user`, which exists only once requireUser has run. Now Theo's delete gets `403` and `{"status":403,"title":"Forbidden","detail":"You need the admin role for that."}`, and Maya's gets `204`. (`sendProblem` sends the course's one error shape, from *Error Handling and Consistent Error Responses*.)

## Ownership, with req.user.id

A role can't say which tasks are Theo's. Each task records its owner's id, `ownerId`, and the edit route compares it with who's asking:

```javascript
app.patch("/tasks/:id", requireUser, (req, res) => {
  const task = tasks.find((t) => t.id === Number(req.params.id));
  if (task === undefined) {
    return sendProblem(res, 404, `There's no task ${req.params.id}.`);
  }
  if (task.ownerId !== req.user.id && req.user.role !== "admin") {
    return sendProblem(res, 403, "Only the task's owner or an admin may change it.");
  }
  task.done = req.body.done;
  res.json(task);
});
```

Admins pass too, because the team decided an admin may fix anyone's task. Theo marking his task 2 done gets `200`; Sofia's task 3 gets `403` and `{"status":403,"title":"Forbidden","detail":"Only the task's owner or an admin may change it."}`. A task that doesn't exist gets 404 first, since it has no owner to compare.

The check uses `req.user.id`, and that matters more than it looks. Here's a version that trusts the request instead:

```javascript
  if (task.ownerId !== req.body.userId) {
```

Theo sends `{ "done": false, "userId": 3 }` to Sofia's task and gets `200`: the check compared Sofia's id with Sofia's id, because Theo typed it. Anything in the body, the address or a header other than the token is whatever the caller chose to send. `req.user.id` came from a token only the server could sign. The same goes for a new task: its owner is `req.user.id`, never `req.body.ownerId`.

## 401 or 403, read as sentences

| Code | Read it as | Crew Board sends it when |
|---|---|---|
| `401 Unauthorized` | I don't know who you are; sign in first | There's no token, a made-up one, or an expired one |
| `403 Forbidden` | I know who you are, and you're not allowed | Theo deletes a task, or edits Sofia's |

The difference tells the app what to do next. After a 401, it shows the sign-in page, because a fresh token may fix it. After a 403, signing in again changes nothing, so it explains instead. (401's name says "Unauthorized", but it means "not authenticated": an old naming slip every API lives with.)

To test the rules, try each one as each kind of user it treats differently, and once with no token. With tokens for Theo and Maya from `before`, as in *Requiring a Signed-In User*:

```javascript
test("DELETE /tasks/3 with no token answers 401", async () => {
  const response = await request(app).delete("/tasks/3");
  assert.equal(response.status, 401);
});

test("DELETE /tasks/3 as Theo, a member, answers 403", async () => {
  const response = await request(app)
    .delete("/tasks/3")
    .set("Authorization", `Bearer ${tokens.theo}`);
  assert.equal(response.status, 403);
});

test("DELETE /tasks/3 as Maya, an admin, answers 204", async () => {
  const response = await request(app)
    .delete("/tasks/3")
    .set("Authorization", `Bearer ${tokens.maya}`);
  assert.equal(response.status, 204);
});
```

```text
✔ DELETE /tasks/3 with no token answers 401 (160.5077ms)
✔ DELETE /tasks/3 as Theo, a member, answers 403 (4.4884ms)
✔ DELETE /tasks/3 as Maya, an admin, answers 204 (3.9559ms)
ℹ tests 3
ℹ suites 0
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 432.1863
```

## Do it: decide who may edit a Crew Board task

Before Crew Board's edit route changes a task, it needs one yes-or-no answer: may this user edit it?

**Your job:** write `canEditTask(user, task)`, which returns `true` when the user may edit the task, and `false` when they may not.

- `user`: the signed-in user, as `req.user` holds them: `{ id, name, role }`. `role` is `"admin"` or `"member"`.
- `task`: the task, `{ id, title, ownerId }`. `ownerId` is the id of the user who owns it.
- An admin may edit any task.
- A member may edit a task only when its `ownerId` is the member's own `id`.

Worked through: Theo is `{ id: 2, name: "Theo", role: "member" }`, and Sofia's task is `{ id: 3, title: "Fix the typo on the sign-in page", ownerId: 3 }`. Theo isn't an admin, and the task's `ownerId`, 3, isn't his `id`, 2, so `canEditTask(theo, sofiasTask)` returns `false`.

Practiced live on the lesson page: write the JavaScript right there and check it.

## Check yourself

2 questions to try on the lesson page.

## So what

The rules about who may do what live on the server, as two kinds of check, role and ownership, and the status code you send tells the app whether signing in again could help.

## Key terms

- [403 Forbidden](https://www.ask-codey.com/glossary/403-forbidden)
- [401 Unauthorized](https://www.ask-codey.com/glossary/401-unauthorized)
- [Authorization](https://www.ask-codey.com/glossary/authorization)
- [Role-Based Access Control](https://www.ask-codey.com/glossary/role-based-access-control-rest-api)
- [Ownership Check](https://www.ask-codey.com/glossary/ownership-check)

## Related

- [Requiring a Signed-In User](https://www.ask-codey.com/lessons/node-auth-require-user-middleware)
- [Tokens: Signing In with a JWT](https://www.ask-codey.com/lessons/node-auth-tokens-jwt)
- [Status Codes and Headers](https://www.ask-codey.com/lessons/node-http-status-codes-and-headers)
- [The Attacks to Expect: Injection and Mass Assignment](https://www.ask-codey.com/lessons/node-security-common-attacks)

Source: https://www.ask-codey.com/lessons/node-auth-roles-and-ownership
