IntermediateLesson 7 of 125 min read

Authorisation: Roles, Ownership and the Difference Between 401 and 403

Decide what each signed-in member may do with roles and ownership rules, return 401 for unknown callers, 403 for forbidden actions and 404 to hide private resources, and test the whole permission matrix against a written specification.

In this lesson you will

  • Separate authentication from authorisation
  • Model roles and ownership
  • Use 401, 403 and 404 correctly
  • Test the whole permission matrix

About 28 minutes

Logged in does not mean allowed

Authentication says who someone is. Authorisation decides what that person may do. They are different questions, and mixing them up is behind many data breaches: a site checks that you are logged in and then lets you read any member’s loans by changing the number in the URL. In Kofi’s library there are three roles. A member may see and return their own loans. A volunteer may see all loans and record returns. An admin may also delete tools and change roles. A rule such as “own loans only” depends on ownership, which is a relationship between the person and the resource, not just a role.

Three status codes express the outcomes, and they are often confused. 401 Unauthorized, despite its name, means “I do not know who you are”: the credentials are missing or invalid. 403 Forbidden means “I know who you are, and you may not do this”. And sometimes the right answer is 404 Not Found, when even revealing that a resource exists would leak information, for example another member’s loan. The permission check belongs in one place, a function that every route calls, and the safest default is to deny: anything not explicitly allowed is refused.

Outcome Status Meaning
No or bad token 401 Who are you?
Valid token, action not allowed 403 You may not
Another member’s private record 404 Pretend it does not exist
Allowed 200 / 204 Proceed
import json
ROLES = {"member": {"loan:read:own", "loan:return:own"},
         "volunteer": {"loan:read:own", "loan:return:own", "loan:read:any", "loan:return:any"},
         "admin": {"loan:read:own", "loan:return:own", "loan:read:any", "loan:return:any", "tool:delete", "role:change"}}
def can(user, action, owner=None):
    if user is None: return "401"
    perms = ROLES.get(user["role"], set())
    if action in ("tool:delete", "role:change"):
        return "200" if action in perms else "403"
    kind, verb = action.split(":")
    if owner is not None and owner == user["id"]:
        return "200" if "loan:%s:own" % verb in perms else "403"
    if "loan:%s:any" % verb in perms: return "200"
    return "404" if verb == "read" else "403"

users = {"nobody": None, "ama": {"id": 1, "role": "member"}, "vera": {"id": 2, "role": "volunteer"}, "kofi": {"id": 3, "role": "admin"}}
actions = [("loan:read", 1), ("loan:read", 9), ("loan:return", 1), ("loan:return", 9), ("tool:delete", None), ("role:change", None)]
matrix = {}
header = "user".ljust(8) + "".join(("%s %s" % (a.split(":")[1] if a.startswith("loan") else a, "own" if o == 1 else "other" if o else "")).strip().ljust(16) for a, o in actions)
print(header)
for name, u in users.items():
    row = [can(u, a, o) for a, o in actions]
    matrix[name] = row
    print(name.ljust(8) + "".join(r.ljust(16) for r in row))
print("DATA " + json.dumps(matrix))
user    read own        read other      return own      return other    tool:delete     role:change     
nobody  401             401             401             401             401             401             
ama     200             404             200             403             403             403             
vera    200             200             200             200             403             403             
kofi    200             200             200             200             200             200             

The matrix shows the result of 24 decisions, one for each user and action. Reading the row for “nobody”: every action gets 401, because the caller is unknown. Ama, a member, may read and return her own loans (200), gets 404 when she tries to read another member’s loan, so that the existence of that loan is not revealed, and gets 403 when she tries to return somebody else’s loan or delete a tool, because those are actions that she knows exist and may not do. The volunteer may read and return any loan but not delete tools or change roles, and the admin may do everything. The function ends with a default of refusal: if an action is not in any of the role’s permission sets, nothing allows it.

Independent check, part one: the specification was written as a separate table, with the expected status for every cell, by reading the rules in words, and compared with the output of the function, cell by cell. All 24 cells agree. This is a good way to test authorisation: write the policy as data, and let a test compare it with the code. Part two: the function was put behind a real HTTP server, and curl sent four requests with different tokens. The unauthenticated one got 401, Ama on her own loan got 200, Ama on somebody else’s loan got 404, and the volunteer on that loan got 200, exactly as the matrix says.

Notice where the check lives. Hiding the “Delete tool” button for members in the front end is a courtesy, not security, since anyone can send the request by hand. The back end checks every request, using data from the verified token and the database, never from fields in the request that the caller controls, such as a “role” value in the body.

Check by hand with Ama: reading her own loan is allowed because the owner id equals her id, and the role member has loan:read:own. Reading loan 9, owned by someone else, needs loan:read:any, which a member lacks, and a read is answered with 404. Returning that loan is not a read, so the answer is 403.

Insecure direct object references are everywhere

Any URL with an id, such as /loans/9, must check that the caller may access that id. Changing a number in a URL is the simplest attack there is, and it works on sites that forgot this check.

Deny by default and keep policy in one place

Write one function or table that decides, call it from every route, and make “no rule” mean “no”. A policy table is also easy to review and to test.

About this course

Every program in this lesson was run while the course was written, with Python 3.13 and only its standard library (http.server, sqlite3, hashlib, hmac), with a real server on a free local port, and cross-checked with curl, openssl or a second implementation. Tools and versions change, so check the official documentation for current behaviour. Real systems often use libraries or services for policies. The structure shown here is the idea behind them.

Practice

Add a “suspended” flag that blocks every action of a member. Add a rule that volunteers cannot return a loan that they own themselves, and update the specification table. Check that the permission function is used by every route of your own API.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does 401 mean?

  1. The action is forbidden
  2. Not found
  3. Server error
  4. The caller is unknown or the credentials are bad

Authentication failed or is missing.

What does 403 mean?

  1. Unknown caller
  2. Not found
  3. Known caller, action not allowed
  4. Created

Authorisation failed.

Why answer 404 for another member’s loan?

  1. Because it is faster
  2. It is the standard
  3. To avoid revealing that it exists
  4. The loan is deleted

Information leak.

Is hiding a button in the front end enough?

  1. Yes
  2. No, the back end must check
  3. Only for admins
  4. Only on phones

Requests can be sent by hand.

What is the safest default for a permission check?

  1. Allow
  2. Deny
  3. Ask the user
  4. Log only

Deny unless explicitly allowed.

Summary

  • Authentication says who, authorisation says what they may do.
  • 401 for unknown callers, 403 for forbidden, 404 to hide private records.
  • Check every request on the back end, and deny by default.
  • Test the whole matrix against a written specification.

Next lesson

Lesson 8 covers pagination, filtering and sorting.

Questions

What is RBAC?

Role-based access control: permissions are given to roles, and users get roles. Many systems add ownership and attributes, such as in the examples here.

Where should the role come from?

From the verified token or the database, never from a value the client sends in the request body or a header you did not sign.

How do I test authorisation?

Write the expected outcomes as a table and compare it with the code for every combination, as this lesson does, and add a test for every new rule.

Progress is saved in this browser.