Roles and Ownership: 401 or 403

Signed in isn't the same as allowed, so a require_role dependency lets only the right role through, an ownership check compares a record's owner with the signed-in user's id, and both answer 403 Forbidden, while 401 stays for a request with no valid token.

Journeyman · FastAPI · REST API · Updated

By

After this lesson you can

  • Write a require_role dependency that answers 403 when the signed-in user's role isn't the one a route needs
  • Check ownership with the signed-in user's 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 one as a sentence

Key takeaways

  • A role, such as member or admin, says what kind of user someone is. It's stored with the user, and get_current_user loads it with them on every request.
  • require_role("admin") makes a dependency that answers 403 for any other role. A route uses it with dependencies=[Depends(require_role("admin"))] on its decorator.
  • An ownership check compares the record's owner with the signed-in user's id, which came from a token only the server can sign. An id in the body is whatever the caller typed.
  • 401 means "I don't know who you are; sign in first." 403 means "I know who you are, and you're not allowed", so signing in again won't help.

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 the 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 ask for user: CurrentUser 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 one. But being signed in is all get_current_user checks. Theo, a member, signs in and sends DELETE /tasks/3, Sofia's task, with his token. It answers 204 No Content: gone. His token was real, so the check at the door let him in, 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 require_role

A role belongs to the user: the users table has a role column, and get_current_user loads it with the rest, as {"id": 2, "name": "Theo", "email": "theo@example.com", "role": "member"}. It comes from the database, found by the id in a signed token, so nothing Theo sends can make him an admin. A second dependency checks it:

def require_role(role):
    def check_role(user: CurrentUser):
        if user["role"] != role:
            raise HTTPException(status_code=403, detail=f"You need the {role} role for that.")
        return user

    return check_role

require_role isn't a dependency 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. The check_role it gives back depends on CurrentUser, so the check at the door always runs first. The delete route puts it on its decorator, since the route itself doesn't need the user:

@router.delete("/{task_id}", status_code=204, dependencies=[Depends(require_role("admin"))])
def delete_task(task_id: int, conn: sqlite3.Connection = Depends(get_db, scope="function")):
    if not crew_data.delete_task(conn, task_id):
        raise HTTPException(status_code=404, detail=f"There's no task {task_id}.")

Now Theo's DELETE /tasks/3 answers 403 Forbidden, and Maya's answers 204:

{"status":403,"title":"Forbidden","detail":"You need the admin role for that."}

Theo's DELETE /tasks/99 answers the same 403, not a 404: the role check runs before the route looks for the task, so a member learns nothing about which tasks exist.

Ownership, with the signed-in user's id

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

@router.patch("/{task_id}")
def change_task(
    task_id: int,
    change: TaskChange,
    user: CurrentUser,
    conn: sqlite3.Connection = Depends(get_db, scope="function"),
):
    task = crew_data.find_task(conn, task_id)
    if task is None:
        raise HTTPException(status_code=404, detail=f"There's no task {task_id}.")
    if task["owner_id"] != user["id"] and user["role"] != "admin":
        raise HTTPException(status_code=403, detail="Only the task's owner or an admin may change it.")
    changed = {**task, **change.model_dump(exclude_unset=True)}
    return crew_data.update_task(conn, task_id, changed["title"], changed["done"])

Admins pass too, because the team decided an admin may fix anyone's task. Theo's PATCH /tasks/2 with {"done": true} answers 200 with his task, now done. The same change to Sofia's task 3 answers 403, with the detail Only the task's owner or an admin may change it. A task that isn't there answers 404 first, since it has no owner to compare.

The check uses user["id"], and that matters more than it looks. Here's a version that trusts the request instead: the TaskChange model gets a user_id field, and the check reads it:

    if task["owner_id"] != change.user_id and user["role"] != "admin":

Theo sends {"done": false, "user_id": 3} to Sofia's task and gets 200 OK: the check compared Sofia's id with Sofia's id, because Theo typed it. Anything in the body, the path, the query string or a header other than the token is whatever the caller chose to send. user["id"] came from a token only the server could sign. The same goes for a new task: the route saves it with user["id"] as its owner, and its model has no owner_id field, so a body that sends one changes nothing.

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 changes 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.)

The checks Theo's DELETE /tasks/3 passes through, in order: oauth2_scheme answers 401 when there's no token, get_current_user answers 401 when the token is made up or expired, require_role answers 403 because Theo is a member, so the route never runs; Maya's same request passes all three and the route answers 204

Do it: decide who may change a task

Crew Board's app grays out the edit button on tasks the person can't change, so it needs the same rule the API uses, as a plain function.

  • user: the signed-in user, a dictionary with the keys id, name and role ("member" or "admin").
  • task: a task, a dictionary with the keys id, title, owner_id and done.

Your job: write can_edit_task(user, task).

  • Return True when the user is an admin, whatever the task.
  • Return True when the task's owner_id is the user's id.
  • Otherwise, return False.

Worked through: Theo is {"id": 2, "name": "Theo", "role": "member"}, and task 2, "Write the release notes", has owner_id 2, so can_edit_task(theo, task_2) returns True. Sofia's task 3 has owner_id 3, so can_edit_task(theo, task_3) returns False.

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

Check yourself

2 questions to try on the lesson page.

So what

A role answers "what kind of user may do this?", an ownership check answers "is this yours?", and as long as both read the user from the token, never from the request, nobody can talk their way past either one.

Key terms

Related