Repository navigation
API Authorization Object Function and Property Level
Last reviewed: 2026-11-28
Caution
Authorized use only. The tests below swap object IDs and roles on purpose. Run them against your own code or the local Secure API lab only, or under a written scope. See LEGAL.md.
Prerequisites: API threat modeling ยท Methodology Phase 5: Authorization Testing
Show how to implement and test the three authorization checks every API needs: per object, per function and per property. These map to OWASP API Security Top 10 2023 API1, API5 and API3. The guide also covers how to keep those checks in one deny-by-default policy instead of scattered if statements.
Explains each check with the matching code from the lab's impl/fixed_api.py. Gives a small, centralized policy module with unit tests (stdlib only, run as written on Python 3.14.10). Lists the test matrix an API needs before release.
Every request is authorized on the server for the specific object, function and fields it touches. A missing rule or a broken rule means "deny", and CI proves it.
- Adding a route, resolver or RPC method that reads or writes user-owned data
- Adding an admin or support function
- Accepting JSON bodies that bind to model objects
- Reviewing an IDOR, BOLA or mass-assignment finding
- The Three Checks
- Object Level: API1
- Function Level: API5
- Property Level: API3
- Centralized Deny-by-Default Policy
- Verification Tests
- Remediation Checklist
| Check | Question | OWASP API 2023 | ASVS 5.0.0 |
|---|---|---|---|
| Object level | May this caller act on this record? | API1:2023 Broken Object Level Authorization | 8.2.2 |
| Function level | May this caller use this operation at all? | API5:2023 Broken Function Level Authorization | 8.2.1 |
| Property level | May this caller read or write these fields? | API3:2023 Broken Object Property Level Authorization | 8.2.3 |
ASVS 8.3.1 adds that the rules must be enforced "at a trusted service layer", never by client-side code. ASVS 8.1.1 and 8.1.2 ask for the rules to be documented, which is also what makes them testable.
Load the object, then check it against the caller, in the same function, on every access. A guessable or sequential ID is not the vulnerability by itself. The vulnerability is the missing check. The OWASP Authorization Cheat Sheet makes the same point: randomizing IDs "is generally not sufficient by itself".
From fixed_api.py (_owned_invoice):
invoice = self.env.invoices.get(int(iid))
if invoice is None or (invoice["owner_id"] != user["id"] and user["role"] != "admin"):
return None, problem(404, "Not Found")- Return the same status for "not yours" and "does not exist" (here 404), so the API does not confirm which IDs exist.
- Apply the same check to writes. In the lab's
bola-read-other-user-recordcase, the vulnerable twin let Alice read and rewrite Bob's invoice (200/200, record changed). The fixed twin answered 404/404 and the record was unchanged. - In list endpoints, filter in the query (
WHERE owner_id = ?), not after loading every row. - In multi-tenant systems, scope every query by tenant as well (ASVS 8.4.1).
Admin and support functions need an explicit role or permission check, in addition to authentication. From _require_admin:
if user is None:
return problem(401, "Unauthorized", headers=[("WWW-Authenticate", 'Bearer realm="lab"')])
if user["role"] != "admin":
return problem(403, "Forbidden")- Use 401 when there is no valid credential and 403 when the credential is valid but not permitted.
- Do not rely on an
/adminURL prefix, a hidden UI button or anX-Adminheader. Inbfla-admin-route, the vulnerable twin let any logged-in user list users and disable Bob (200/200). The fixed twin returned 403/403. - Check the HTTP method too. A route that checks the role on
GETbut not onDELETEis a function-level flaw (ASVS 4.1.4 also asks that unsupported methods are blocked).
API3:2023 merges two older problems: writing fields you should not (mass assignment) and reading fields you should not (excessive data exposure).
Writes: allowlist the writable fields and refuse the rest.
WRITABLE_PROFILE_FIELDS = {"display_name"}
extra = sorted(set(body) - WRITABLE_PROFILE_FIELDS)
if extra:
return problem(400, "Bad Request", "read-only or unknown properties", invalid_fields=extra)The OWASP Mass Assignment Cheat Sheet recommends dedicated input objects (DTOs) or explicit allowlists and warns against block-lists, since "a new or overlooked sensitive field remains bindable". Refusing with 400, rather than silently dropping unknown fields, makes the client bug visible and the test simple.
Reads: build responses from an explicit list of public fields.
PUBLIC_PROFILE_FIELDS = ("id", "display_name")
return json_response(200, {k: user[k] for k in PUBLIC_PROFILE_FIELDS})Never serialize the storage model directly. In bopla-excessive-data-exposure, the vulnerable twin returned email, mfa_secret and password_hash, and the fixed twin returned only id and display_name. If different callers may see different fields (owner versus public), make the field list a function of the policy decision, not of the client's request.
The OWASP Authorization Cheat Sheet asks applications to "deny access by default" and to validate permissions "on every request", using a mechanism that allows "global, application-wide configuration". One way to do that in plain Python is a single table of rules keyed by action and resource type, where a missing key or a rule that raises an exception both mean "deny":
from dataclasses import dataclass
from typing import Callable
@dataclass(frozen=True)
class Subject:
id: int
role: str
Rule = Callable[[Subject, dict], bool]
# One table: (action, resource type) -> rule. Anything not listed is denied.
POLICY: dict[tuple[str, str], Rule] = {
("read", "invoice"): lambda s, r: r["owner_id"] == s.id or s.role == "admin",
("update", "invoice"): lambda s, r: r["owner_id"] == s.id,
("list", "user"): lambda s, r: s.role == "admin",
}
def is_allowed(subject: Subject | None, action: str, rtype: str, resource: dict) -> bool:
if subject is None:
return False
rule = POLICY.get((action, rtype))
if rule is None:
return False # deny by default
try:
return rule(subject, resource) is True
except Exception:
return False # a broken rule never grants accessDesign notes:
-
is Truematters. A rule that returns a truthy non-boolean by mistake, such as a non-empty list, must not grant access. - Handlers call
is_allowedand never re-implement the rule. Reviewers then check one table, and tests cover one function. - If the decision comes from a remote policy service, an exception or timeout must also deny. The lab's
get_reportreturns 503 withRetry-Afterwhen the policy service is down. Its vulnerable twin served the report (fail-closed-authz-exception). See secure error handling. - Decide from the originating caller's identity, not from the identity of a service in between (ASVS 8.3.3). Apply changes to roles immediately, or add a mitigation where tokens carry stale claims (ASVS 8.3.2).
Write the matrix of subject, action and expected result as data and test all of it. This test runs against the policy above (python3 -m unittest):
import unittest
class PolicyMatrix(unittest.TestCase):
alice, bob, admin = Subject(1, "user"), Subject(2, "user"), Subject(9, "admin")
bobs_invoice = {"id": 7, "owner_id": 2}
def test_matrix(self):
cases = [
(self.bob, "read", "invoice", True),
(self.alice, "read", "invoice", False), # BOLA
(self.admin, "read", "invoice", True),
(self.admin, "update", "invoice", False), # admins read, owners write
(self.alice, "list", "user", False), # BFLA
(self.alice, "delete", "invoice", False), # unknown action: denied
(None, "read", "invoice", False),
]
for subject, action, rtype, expected in cases:
with self.subTest(subject=subject, action=action):
self.assertIs(is_allowed(subject, action, rtype, self.bobs_invoice), expected)
def test_rule_error_denies(self):
self.assertFalse(is_allowed(self.bob, "read", "invoice", {})) # KeyError inside ruleAt the HTTP level, add these for every route:
| Test | Expected |
|---|---|
| User A requests user B's object by ID (read, update, delete) | 404 or 403, and a follow-up read as B shows the object unchanged |
| Non-admin calls each admin route with each method | 403 |
Body includes role, owner_id, is_admin or any field not in the allowlist |
400, stored values unchanged |
| Response for another user's public profile | Only the documented public fields |
| Policy dependency raises or times out | Denied (503 or 403), logged server-side |
| Owner requests own object | 200, so the negative tests cannot pass because the route is simply broken |
The lab's bola-*, bfla-* and bopla-* cases follow this pattern over HTTP on 127.0.0.1, including the "state unchanged" check after a write.
- One policy module; handlers call it; missing rules deny
- Object ownership or tenant check on every read and write, in the data query for lists
- Explicit role or permission check on every admin function and method
- Writable-field allowlist (DTO); unknown fields refused
- Response field allowlist per caller type
- Policy errors and timeouts deny; failed decisions logged (ASVS 16.3.2)
- Matrix tests in CI, with positive controls
- OWASP API Security Top 10 2023: API1, API3, API5
- OWASP ASVS 5.0.0 V8 Authorization
- OWASP Authorization Cheat Sheet
- OWASP Mass Assignment Cheat Sheet
- OWASP Top 10:2025 A01 Broken Access Control
- Secure error handling
- Webhooks, GraphQL & gRPC: authorization inside resolvers and interceptors
- README.md - Web Application Security index
- labs/secure-api/impl/fixed_api.py - Fixed handlers quoted above
- labs/secure-api/README.md - Lab cases and CI evidence
โฌ ๏ธ Web Application Security index | Master Index | ๐ฏ Role Navigation | Legal Notice
๐ Source: WebAppSecurity/api-authorization.md | โ๏ธ Suggest an edit | โฌ
๏ธ Back to Web App Security
- ๐บ๏ธ Browse by Topic
- ๐ All Repository Files
- ๐งญ Learning Paths
- ๐ Master Guide
- ๐ค Glossary
- โ๏ธ Legal & Disclaimer
๐ Foundations & Learning
๐ก๏ธ Defense & Investigations
- Incident Response
- Open Source Intelligence (OSINT)
- Reverse Engineering
- Operations Security (OPSEC)
- Compliance
โ๏ธ Platforms & Infrastructure
๐ก Hardware, Wireless & Field Projects
- PNWC Cyberdeck
- Hardware Testing
- Hardware Hacking
- Software-Defined Radio
- Wardriving
- uConsole
- Space Security
๐งฐ Assessment & Field Reference
๐ฆ Downloads & Project Resources
๐๏ธ Additional Topics