API authorization
medium 24 minAuthorization decides what a known caller may do, to which object, right now.
See it run
Roles, owners, situations and scopes: follow each decision to allow or deny.
Operations
Read a role's rights
The permission matrix of a shop, one role at a time.
Step 1 of 5
Customer
| Customer | Seller | Admin | |
|---|---|---|---|
| View products | yes | yes | yes |
| Create product | no | yes | yes |
| Edit product | no | own | yes |
| Delete product | no | no | yes |
| Own cart | own | no | yes |
| Place order | yes | no | yes |
| View orders | own | own sales | yes |
| Manage users | no | no | yes |
Customers view products and place orders. Cart and orders are their own only.
Step 1: Customer
def permissions_of(user): found = set(user.permissions) for role in user.roles: found |= ROLE_PERMISSIONS.get(role, set()) return found- Needs
- Role only
- Denied with
- 403
Each cell that says own needs a second check.
In the real world
The same api authorization doing real jobs. Pick one and step through it.
The most common authorization hole, and its fix.
Step 1 of 3
Their own order
| Owner | Asked by | Answer | |
|---|---|---|---|
| 1001 | Ann | Ann | 200 |
| 1002 | Ben | - | - |
Ann asks for order 1001, which is Ann's.
Step 1: Their own order
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Checking only in the browser
criticalAnyone can call the API without your page.
Wrongif user.role == "admin": show_delete_button()Rightdef delete(user, id): if not allowed(user, "products:delete"): return 403Forgetting the object
criticalA logged-in user changes an ID and sees other people's data.
Wrongorder = db.get(order_id)Rightorder = db.get(order_id, tenant=user.tenant, customer=user.id)Allowing by default
criticalEvery new action is open until someone remembers to block it.
Wrongif action in blocklist: return Falsereturn TrueRightreturn action in allowlistAdmin for one small need
majorOne stolen account then holds everything.
Wronguser.roles.append("admin")Rightuser.permissions.add("reports:read")
Interview tips
Explain it in one line
- What may this caller do, to which object, right now?
GUARD
- Grant minimum.
- Use roles.
- Always server-side.
- Reject by default.
- Document scopes.
Choose the model
- Few jobs: roles and ownership.
- Time, place, state: attributes.
- Sharing: relationships.
- Other apps: scopes.
Expect these questions
- How do you isolate tenants?
- What if a role is removed?
- How do you check a list?