SyntaxPilot
Courses/Cybersecurity Fundamentals/Lesson 49
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Cybersecurity Fundamentals · Lesson 49 of 90

API security part 1: OWASP API Top 10 (1-3)

RESTGraphQL and gRPC attack surfaceOWASP API Security Top 10 2023API1 broken object level authorization (BOLA)API2 broken authenticationAPI3 broken object property level authorization (BOPLA)mass assignmentexcessive data exposureAPI keys vs tokensresponse filtering with DTOs

These are the notes for Cybersecurity Fundamentals (defensive), episode 49. Episode 48 defended the login page. Today we go behind the app, to the API it talks to, and cover the first three risks of the OWASP API Security Top 10 (2023): broken object level authorization, broken authentication, and broken object property level authorization. Every term is explained the first time it appears, and the Glossary at the end defines them all again.

Neha, Ravi, Asha, the shop, the addresses and every value are made up. The three "API styles" are plain Python functions that copy the shape of each style's requests, and nothing outside the machine is contacted. The Python samples were run on 12 Nov 2026 with Python 3.13, and every output below is copied from a real run.

The problems you'll solve

Problem Idea it teaches
A check on the REST door is missing from the GraphQL and gRPC doors API, endpoint, REST, GraphQL, gRPC, attack surface
Which API risks matter most? the OWASP API Security Top 10 2023
Changing order 501 to 502 shows Ravi's address API1 broken object level authorization (BOLA), object-level checks
A token that just says {"user": "admin"} is believed API2 broken authentication, signed and expiring tokens
An API key used to identify users API keys vs tokens
The profile screen shows 2 fields but the response has 7 API3 BOPLA: excessive data exposure, response DTOs
"is_admin": true in an edit request is accepted API3 BOPLA: mass assignment, update DTOs

What an API is

Real-life example: in a restaurant you don't walk into the kitchen. You tell the waiter, and the waiter brings the food.

  • An API (application programming interface) is a fixed way for one program to ask another program for something. The shop's mobile app never touches the database. It asks the server's API.
  • An endpoint is one thing you can ask for: an address plus an action, for example GET /api/orders/501 ("give me order 501"). It's like one dish on the menu.
  • A request is what the caller sends (the order slip), and a response is what comes back (the plate).
  • JSON (JavaScript Object Notation) is a simple text format of names and values in curly brackets, for example {"name": "Ravi", "city": "Kolkata"}. Most APIs send JSON.
  • Anyone can call an API, not just your app. Any program that can send HTTP requests can write its own "order slip". So every check must happen on the server, never only in the app (see "never trust the client", episode 36).

REST, GraphQL and gRPC: three kinds of door

  • REST gives every thing (called a resource) its own URL and uses the HTTP methods from episode 21: GET to read, POST to create, PATCH/PUT to change, DELETE to remove. Example: GET /api/orders/502, PATCH /api/users/me.
  • GraphQL, in the words of graphql.org, "is a query language for your API, and a server-side runtime for executing queries using a type system you define for your data". There is usually one URL, and the client writes a query that names the fields it wants, for example { order(id: 502) { item address } }. The client gets "just that data in the expected shape with a single request".
  • gRPC is a remote procedure call system: a client can "call a method on a server application on a different machine as if it were a local object". "By default, gRPC uses Protocol Buffers". Protocol Buffers are typed, structured messages defined in advance, for example rpc GetOrder(OrderRequest) returns (Order).
  • Attack surface (episode 1) is every place an attacker can try to get in. For an API that means every door (REST, GraphQL, gRPC), every endpoint, every version, every parameter and every field. More doors means more surface.

Demo 1: three doors, one check

# One shop, three API styles. Each one is another front door.
import re
from dataclasses import dataclass
ORDERS = {501: ("neha", "kurta"), 502: ("ravi", "headphones")}

def rest(user, path):                     # REST: GET /api/orders/502
    oid = int(path.rsplit("/", 1)[1])
    if ORDERS[oid][0] != user: return "404 not found"   # checked here
    return ORDERS[oid][1]

def graphql(user, query):                 # GraphQL: one URL, a query
    oid = int(re.search(r"id: (\d+)", query)[1])
    return ORDERS[oid][1]                 # added later... no check!

@dataclass
class OrderRequest: id: int               # gRPC: a typed message
def grpc_get_order(user, req):            # rpc GetOrder(OrderRequest)
    return ORDERS[req.id][1]              # no check here either

print("REST    ->", rest("neha", "/api/orders/502"))
print("GraphQL ->", graphql("neha", "{ order(id: 502) { item } }"))
print("gRPC    ->", grpc_get_order("neha", OrderRequest(id=502)))

Real output:

REST    -> 404 not found
GraphQL -> headphones
gRPC    -> headphones

Why it failed: the ownership check lived inside one door (REST) instead of in front of the data. When the GraphQL and gRPC doors were added later, nobody repeated it. Fix: put the check in one shared function that every door must call to load an order (Practice 1 and the mini project).

The OWASP API Security Top 10 (2023)

OWASP (the Open Worldwide Application Security Project, episode 36) keeps a separate list just for APIs. The 2023 edition is the second edition, released four years after the first (2019).

# Risk Episode
API1:2023 Broken Object Level Authorization 49 (today)
API2:2023 Broken Authentication 49 (today)
API3:2023 Broken Object Property Level Authorization 49 (today)
API4:2023 Unrestricted Resource Consumption 50
API5:2023 Broken Function Level Authorization 50
API6:2023 Unrestricted Access to Sensitive Business Flows 50
API7:2023 Server Side Request Forgery 50
API8:2023 Security Misconfiguration 50
API9:2023 Improper Inventory Management 50
API10:2023 Unsafe Consumption of APIs 50

In 2023 OWASP merged the 2019 items Excessive Data Exposure and Mass Assignment into API3, because of their "common root cause: object property level authorization validation failures".

API1: broken object level authorization (BOLA)

Real-life example: a wedding cloakroom gives you token 501 for your bag. If you write 502 on the token and the attendant only looks at the number, you walk away with a stranger's bag.

  • An object is one stored record, for example one order. An object ID is the number or code that names it, for example 501 in /api/orders/501.
  • Authorization means deciding what an already-identified user is allowed to do (episode 30). Being logged in is not the same as being allowed.
  • BOLA (API1:2023) happens when an API returns or changes an object without checking that the caller may access that object. OWASP: "APIs tend to expose endpoints that handle object identifiers". In web apps the same bug is called IDOR, insecure direct object reference (episode 37).
  • OWASP's examples include a URL pattern like /shops/{shopName}/revenue_data.json that let one shop read every other shop's revenue, a car unlocked by its VIN with no ownership check, and a GraphQL mutation that deleted other users' documents.

Demo 2: changing 501 to 502

# A toy shop API. GET /api/orders/<id> returns one order as JSON.
ORDERS = {501: {"id": 501, "owner": "neha", "item": "kurta",
                "address": "12 MG Road, Pune"},
          502: {"id": 502, "owner": "ravi", "item": "headphones",
                "address": "4 Park Street, Kolkata"}}

def get_order_v1(user, order_id):           # logged in? then here you go
    order = ORDERS.get(order_id)
    return (200, order) if order else (404, {"error": "not found"})

def get_order_v2(user, order_id):           # is this order YOURS?
    order = ORDERS.get(order_id)
    if order is None or order["owner"] != user:
        return 404, {"error": "not found"}    # same answer: no hint
    return 200, order

for fn in (get_order_v1, get_order_v2):
    for oid in (501, 502):                    # Neha asks for 501, then 502
        status, body = fn("neha", oid)
        shown = body.get("address", body.get("error"))
        print(f"{fn.__name__} order {oid}: {status} {shown}")

Real output:

get_order_v1 order 501: 200 12 MG Road, Pune
get_order_v1 order 502: 200 4 Park Street, Kolkata
get_order_v2 order 501: 200 12 MG Road, Pune
get_order_v2 order 502: 404 not found

Why it failed: v1 checked only that the order existed. Order numbers count up by one, so a script could ask for 1, 2, 3... and collect every customer's address.

Stopping BOLA everywhere

  • IDs from the client hide in many places: the path, the query string, the body, a GraphQL argument, a gRPC message. Every one needs the same check: can this user do this action on this record? OWASP says to use the authorization mechanism in every function that uses input from the client to access a record.
  • Answer 404 not found both for "not yours" and "doesn't exist", so a stranger can't even learn that an order exists.
  • Random IDs: OWASP says to "Prefer the use of random and unpredictable values as GUIDs for records' IDs". A UUID (or GUID) is a 128-bit identifier, for example 3f2b8c1e-.... It makes guessing harder, but IDs leak in links, logs and screenshots, so a random ID is never the check itself.
  • Tests: log in as user A and try to read and change user B's records. OWASP: "Do not deploy changes that make the tests fail."

API2: broken authentication

Real-life example: a guard who believes a handwritten note saying "I'm the boss" lets anyone in. A real visitor pass carries reception's stamp and is valid only today.

  • Authentication means proving who you are (episode 28). APIs usually don't show a login page on every request. The app logs in once, gets a token, and sends it with every request.
  • A token is a string that proves who the caller is. A bearer token works for whoever holds ("bears") it (episode 31).
  • Broken authentication (API2:2023): "Authentication mechanisms are often implemented incorrectly". OWASP lists, among others, APIs that accept unsigned or weakly signed JWT tokens, don't validate the JWT expiration date, use weak or predictable tokens, or allow credential stuffing.
  • Base64 (episode 10) is encoding, not encryption. Anyone can decode it and anyone can write it.
  • A signed token carries a signature, here an HMAC (episode 12): a keyed hash that only someone with the server's secret can compute. If anyone changes a single character, the signature no longer matches.
  • Expiry (exp) is the time after which the token stops working, so a stolen token is useful only for a short while.
  • Constant-time comparison (hmac.compare_digest) takes the same time wherever two strings differ, so timing leaks nothing (episode 27).

Demo 3: forged and expired tokens

# Who is calling the API? Every request carries a token.
import base64, hmac, json
SECRET = b"server-only-secret-32-bytes-long!"   # toy: kept in a vault

def b64(d): return base64.urlsafe_b64encode(json.dumps(d).encode()).decode()

def check_v1(token):                     # just read what it says
    return json.loads(base64.urlsafe_b64decode(token))["user"]

def sign(d): return hmac.new(SECRET, d.encode(), "sha256").hexdigest()
def issue(user, now):                    # signed, expires in 15 min
    body = b64({"user": user, "exp": now + 900})
    return body + "." + sign(body)
def check_v2(token, now):
    body, _, sig = token.partition(".")
    if not hmac.compare_digest(sign(body), sig): return "401 bad signature"
    claims = json.loads(base64.urlsafe_b64decode(body))
    if now > claims["exp"]: return "401 token expired"
    return claims["user"]

forged = b64({"user": "admin"})          # anyone can write this
print("v1 forged token ->", check_v1(forged))
print("v2 forged token ->", check_v2(forged + ".00", now=0))
real = issue("neha", now=0)
print("v2 Neha's token ->", check_v2(real, now=60))
print("v2 an hour later ->", check_v2(real, now=3600))

Real output:

v1 forged token -> admin
v2 forged token -> 401 bad signature
v2 Neha's token -> neha
v2 an hour later -> 401 token expired

Why it failed: v1 checked what the token said, not who made it. OWASP's advice is "Don't reinvent the wheel in authentication, token generation, or password storage". Use a well-tested library (for JWTs, one that pins the algorithm and checks exp, aud and iss, episode 31). Treat forgot-password endpoints like login endpoints, protect them against brute force (episode 48), and use MFA where possible.

API keys vs tokens

Real-life example: a company's delivery account number tells the courier which company is sending, not which employee.

API key User token
Names a program or project ("the shop app") one user ("Neha")
Lifetime long-lived, often months short-lived, minutes to hours
Good for counting usage, quotas, billing, which client is calling who the user is and what they may do
Where it lives often baked into the app, where anyone can dig it out issued after login, kept by that user's app
Permissions the same for every copy of the app scopes: the permissions granted to that token (episode 32)

OWASP is blunt: "API keys should not be used for user authentication." Two more points from OWASP:

  • Re-authentication: for sensitive operations, such as changing the account's email address or 2FA phone number, ask for the password or MFA again.
  • Service-to-service calls need authentication too. OWASP lists APIs that "Other microservices can access ... without authentication" as vulnerable. Inside the network is not the same as trusted (see zero trust, episode 35).

API3: broken object property level authorization (BOPLA)

  • A property is one named field of an object, for example email or is_admin in a user record.
  • BOPLA (API3:2023) is "the lack of or improper authorization validation at the object property level". It has two halves: reading properties you shouldn't see (excessive data exposure), and writing properties you shouldn't set (mass assignment).

Part 1: excessive data exposure

Real-life example: Ravi's public profile screen shows his name and city. The API response behind it has seven fields. The app just doesn't draw the other five, but anyone who reads the raw response (with the browser's developer tools or any HTTP client) sees everything.

  • Serialisation means turning an object into text such as JSON so it can be sent. Serialising the whole database object sends every field in it.
  • A DTO (data transfer object) is a small class or structure that holds only the fields one response is allowed to carry.

Demo 4: a response DTO

# GET /api/users/ravi : the profile page shows only name and city.
import json
USERS = {"ravi": {"name": "Ravi", "city": "Kolkata",
                  "email": "ravi@example.in", "phone": "98xxxxxx12",
                  "password_hash": "$argon2id$v=19$...", "is_admin": False,
                  "kyc_note": "PAN checked by staff"}}

def profile_v1(username):               # send the whole object
    return json.dumps(USERS[username])  # the app "hides" the rest

class PublicProfile:                    # a DTO: only what the page needs
    FIELDS = ("name", "city")
    def __init__(self, user):
        self.data = {f: user[f] for f in self.FIELDS}

def profile_v2(username):
    return json.dumps(PublicProfile(USERS[username]).data)

print("v1 sends:")
for key, value in json.loads(profile_v1("ravi")).items():
    print("   ", key, "=", value)
print("v2:", profile_v2("ravi"))

Real output:

v1 sends:
    name = Ravi
    city = Kolkata
    email = ravi@example.in
    phone = 98xxxxxx12
    password_hash = $argon2id$v=19$...
    is_admin = False
    kyc_note = PAN checked by staff
v2: {"name": "Ravi", "city": "Kolkata"}

Why it failed: v1 let the database decide what leaves the server. OWASP warns against generic methods "such as to_json() and to_string()" and asks you to pick the fields to return. A response DTO is an allowlist (episode 36): a column added to the database next year stays inside unless someone decides it should go out. In one of OWASP's own examples, a dating app's report-a-user response leaked the reported user's full name and recent location.

Part 2: mass assignment

Real-life example: on a bank form to change your address, you also write "balance = 1 lakh" in the margin. A careless clerk copies everything on the form into your account. A careful clerk reads only the address box.

  • Mass assignment happens when the server copies every field in the request into the stored object, including fields the user should never set, like is_admin or wallet.
  • Auto-binding is when a framework does that copying for you automatically, request field to object field.
  • An update DTO is an allowlist of the fields a user may change, with their types checked (text, number, and so on).
  • 400 Bad Request is the HTTP status code for a request the server refuses because it's malformed or not allowed.

Demo 5: mass assignment

# PATCH /api/users/me  {"name": "..."}  lets Ravi edit his profile.
USER = {"name": "Ravi", "city": "Kolkata", "is_admin": False,
        "wallet": 0}

def update_v1(user, body):              # copy every field we were sent
    user.update(body)                   # "auto-binding": mass assignment
    return 200, user

EDITABLE = {"name": str, "city": str}   # the update DTO: an allowlist
def update_v2(user, body):
    extra = set(body) - set(EDITABLE)
    if extra:
        return 400, f"not allowed: {sorted(extra)}"
    for field, kind in EDITABLE.items():
        if field in body and not isinstance(body[field], kind):
            return 400, f"{field} must be text"
    user.update(body)
    return 200, user

def show(result):
    status, u = result
    if isinstance(u, str): return f"{status} {u}"
    keys = ("name", "is_admin", "wallet")
    return f"{status} " + " ".join(f"{k}={u[k]}" for k in keys)

attack = {"name": "Ravi K", "is_admin": True, "wallet": 100000}
print("v1:", show(update_v1(dict(USER), attack)))
print("v2:", show(update_v2(dict(USER), attack)))
print("v2:", show(update_v2(dict(USER), {"city": "Pune"})))

Real output:

v1: 200 name=Ravi K is_admin=True wallet=100000
v2: 400 not allowed: ['is_admin', 'wallet']
v2: 200 name=Ravi is_admin=False wallet=0

Why it failed: v1 let the client decide which properties to write. OWASP: avoid functions that automatically bind client input to internal objects, and accept changes only to the properties the client should be able to update. Rejecting unknown fields, instead of silently dropping them, also shows you who is probing. OWASP's own examples include a booking host who added total_stay_price to an approval request, and a user who sent "blocked": false to unblock their own video.

Response filtering with DTOs, in both directions

request (JSON in) -> update DTO (allowed fields) -> object (database) -> response DTO (allowed fields) -> response (JSON out)
  • The object in the middle never touches the outside directly.
  • One DTO per reader and action: a public profile, your own profile, an admin view (Practice 2).
  • A schema is a written description of every field and its type. OWASP suggests response schema validation as an extra layer, and we use one in episode 50.
  • In GraphQL, where the client picks the fields, check permission for each field, not just for the query.

The whole chain

  1. GraphQL and gRPC doors skipped the check, so check at the data, in one shared function.
  2. 502 gave away Ravi's address, so every object ID gets an ownership check and a 404.
  3. A token that said admin was believed, so tokens are signed and expire, and API keys never stand in for users.
  4. 7 fields were sent to show 2, so responses go through a response DTO.
  5. is_admin: true was copied in, so updates go through an update DTO allowlist.

Common mistakes

Mistake What happened (real output) Why Fix
The check lives in the REST handler only GraphQL -> headphones and gRPC -> headphones other doors skipped it one shared load_order(user, id)
return ORDERS.get(order_id) get_order_v1 order 502: 200 4 Park Street, Kolkata no ownership check owner == user, else 404
Sequential IDs treated as secret a script asks for 1, 2, 3... IDs are guessable the check, plus random UUIDs
json.loads(b64decode(token)) v1 forged token -> admin unsigned token believed verify signature, then exp
No expiry check (a stolen token works forever) no exp 401 token expired after exp
API key used as the user's identity every copy of the app is the "same user" keys name programs user tokens with scopes
json.dumps(USERS[username]) password_hash = $argon2id$v=19$... whole object sent response DTO
user.update(body) v1: 200 name=Ravi K is_admin=True wallet=100000 every field bound update DTO allowlist
GraphQL authorizes the query, not the fields any field can be requested field-level gap check each field

Mini project: one check, three doors, DTOs

A tiny order API where REST, GraphQL-style and gRPC-style handlers all call one authorize() and send data only through a DTO. The GraphQL door also refuses fields that aren't in the DTO.

# Mini project: a tiny order API with ONE shared authorize() check,
# three API-style doors (REST, GraphQL-like, gRPC-like) and DTOs.
import re
from dataclasses import dataclass

ORDERS = {501: {"owner": "neha", "item": "kurta", "address": "12 MG Road, Pune",
                "internal_margin": 0.31},
          502: {"owner": "ravi", "item": "headphones",
                "address": "4 Park Street, Kolkata", "internal_margin": 0.18}}

def authorize(user, order_id):            # the ONE check every door calls
    order = ORDERS.get(order_id)
    if order is None or order["owner"] != user:
        return None                         # caller answers 404 either way
    return order

ORDER_DTO = ("item", "address")             # fields allowed out
def to_dto(order): return {f: order[f] for f in ORDER_DTO}

def rest(user, path):                       # GET /api/orders/502
    order = authorize(user, int(path.rsplit("/", 1)[1]))
    return to_dto(order) if order else "404 not found"

def graphql(user, query):                   # { order(id: 502) { item } }
    oid = int(re.search(r"id: (\d+)", query)[1])
    fields = re.search(r"\{\s*([\w\s]+)\}\s*\}$", query)[1].split()
    order = authorize(user, oid)
    if order is None: return "404 not found"
    bad = [f for f in fields if f not in ORDER_DTO]
    if bad: return f"403 field not allowed: {bad}"
    return {f: order[f] for f in fields}

@dataclass
class OrderRequest: id: int
def grpc_get_order(user, req):              # rpc GetOrder(OrderRequest)
    order = authorize(user, req.id)
    return to_dto(order) if order else "NOT_FOUND"

for who in ("neha", "ravi"):
    print(who, "REST    ->", rest(who, "/api/orders/501"))
print("neha GraphQL ->", graphql("neha", "{ order(id: 501) { item } }"))
print("neha GraphQL ->", graphql("neha", "{ order(id: 501) { internal_margin } }"))
print("neha GraphQL ->", graphql("neha", "{ order(id: 502) { item } }"))
print("neha gRPC    ->", grpc_get_order("neha", OrderRequest(id=502)))

Real output:

neha REST    -> {'item': 'kurta', 'address': '12 MG Road, Pune'}
ravi REST    -> 404 not found
neha GraphQL -> {'item': 'kurta'}
neha GraphQL -> 403 field not allowed: ['internal_margin']
neha GraphQL -> 404 not found
neha gRPC    -> NOT_FOUND

Practice

  1. Fix the two open doors from Demo 1 (GraphQL and gRPC) so that all three use the same check.
  2. Add DTOs for three readers: public, self and admin. The password hash must never leave in any of them.
  3. Make the token check reject a token that has no exp (or an exp that isn't a number).
  4. In Demo 5, what happens if an attacker sends {"city": 42}? Why does the type check matter?
Practice 1 solution
# Practice 1 solution: every door calls the same load_order() check
import re
from dataclasses import dataclass
ORDERS = {501: ("neha", "kurta"), 502: ("ravi", "headphones")}

def load_order(user, oid):                # the one shared check
    if oid not in ORDERS or ORDERS[oid][0] != user:
        return "404 not found"
    return ORDERS[oid][1]

def rest(user, path):
    return load_order(user, int(path.rsplit("/", 1)[1]))
def graphql(user, query):
    return load_order(user, int(re.search(r"id: (\d+)", query)[1]))
@dataclass
class OrderRequest: id: int
def grpc_get_order(user, req):
    return load_order(user, req.id)

print("REST    ->", rest("neha", "/api/orders/502"))
print("GraphQL ->", graphql("neha", "{ order(id: 502) { item } }"))
print("gRPC    ->", grpc_get_order("neha", OrderRequest(id=502)))
print("own     ->", graphql("neha", "{ order(id: 501) { item } }"))
REST    -> 404 not found
GraphQL -> 404 not found
gRPC    -> 404 not found
own     -> kurta

The check now lives in front of the data, so a fourth door added later is safe as long as it loads orders through load_order.

Practice 2 solution
# Practice 2 solution: one DTO per reader
USER = {"name": "Ravi", "city": "Kolkata", "email": "ravi@example.in",
        "phone": "98xxxxxx12", "password_hash": "$argon2id$v=19$...",
        "is_admin": False, "kyc_note": "PAN checked by staff"}
DTOS = {"public": ("name", "city"),
        "self":   ("name", "city", "email", "phone"),
        "admin":  ("name", "city", "email", "is_admin", "kyc_note")}

def view(user, reader):
    return {f: user[f] for f in DTOS[reader]}   # password_hash: never

for reader in DTOS:
    print(f"{reader:6} ->", view(USER, reader))
public -> {'name': 'Ravi', 'city': 'Kolkata'}
self   -> {'name': 'Ravi', 'city': 'Kolkata', 'email': 'ravi@example.in', 'phone': '98xxxxxx12'}
admin  -> {'name': 'Ravi', 'city': 'Kolkata', 'email': 'ravi@example.in', 'is_admin': False, 'kyc_note': 'PAN checked by staff'}
Practice 3 solution
# Practice 3 solution: a token with no "exp" is rejected
import base64, hmac, json
SECRET = b"server-only-secret-32-bytes-long!"
def b64(d): return base64.urlsafe_b64encode(json.dumps(d).encode()).decode()
def sign(d): return hmac.new(SECRET, d.encode(), "sha256").hexdigest()
def make(claims): body = b64(claims); return body + "." + sign(body)

def check_v3(token, now):
    body, _, sig = token.partition(".")
    if not hmac.compare_digest(sign(body), sig): return "401 bad signature"
    claims = json.loads(base64.urlsafe_b64decode(body))
    exp = claims.get("exp")
    if not isinstance(exp, int): return "401 no expiry"   # fail closed
    if now > exp: return "401 token expired"
    return claims["user"]

print(check_v3(make({"user": "neha", "exp": 900}), now=60))
print(check_v3(make({"user": "neha"}), now=60))
print(check_v3(make({"user": "neha", "exp": "never"}), now=60))
neha
401 no expiry
401 no expiry

A missing or malformed expiry fails closed: the token is refused instead of living forever.

Practice 4 solution

update_v2 returns 400 city must be text. Without the type check, a number, a list or a huge nested object could be stored in a text field and break other code that reads it later (or slip past validation that expects text). An update DTO checks both which fields arrive and what kind of value each one holds.

Quick quiz

# PUT /api/videos/77   (Asha owns video 77)
def update_video(user, video_id, body):
    video = VIDEOS[video_id]
    if video.owner != user: return 404
    video.__dict__.update(body)   # body: {"title": "..", "blocked": false}
    return 200

Which OWASP API risk is this? A: API1 BOLA. B: API2 Broken Authentication. C: API3 BOPLA. D: none, it checks the owner.

Answer

C. The owner check stops BOLA, but every field in the body is copied into the video, so Asha can send "blocked": false and unblock her own blocked video. That's mass assignment, part of API3 BOPLA (one of OWASP's own API3 scenarios). Fix: an update DTO that allows only title and description.

Interview questions

  1. What is BOLA and how do you prevent it? The API returns or changes an object named by a client-supplied ID without checking that the caller may access it. Prevent it with an object-level authorization check in every function that loads a record from client input, the same 404 for "not yours" and "doesn't exist", and tests where user A tries user B's records.
  2. BOLA vs IDOR? The same flaw. IDOR is the older web-app name, and BOLA is the OWASP API Top 10 name.
  3. Are random UUIDs enough to stop BOLA? No. They slow down guessing, but IDs leak through links, logs and shared screenshots. The authorization check is the fix.
  4. Why shouldn't API keys authenticate users? A key names a program or project, is long-lived, and is shared by every copy of the app (often extractable from it), so it can't tell one user from another. Use short-lived, signed user tokens with scopes.
  5. What must a server check on a JWT? The signature with a pinned algorithm and the right key, the expiry (exp), and also the issuer (iss) and audience (aud). Never trust the claims before the signature verifies.
  6. What is BOPLA? Broken Object Property Level Authorization (API3:2023): missing checks on individual fields, either reading them (excessive data exposure) or writing them (mass assignment).
  7. How do you prevent excessive data exposure? Never serialise whole internal objects. Return a response DTO with the fields that reader needs, and optionally validate responses against a schema.
  8. What is mass assignment and how do you prevent it? Binding every request field to an internal object. Use an update DTO that allowlists editable fields and checks their types, and reject unknown fields.
  9. Your API has REST and GraphQL endpoints over the same data. Where should authorization live? In a shared layer in front of the data (or in the data-access functions), so every door enforces the same rules. In GraphQL, authorize each field too.
  10. When should an API ask the user to log in again? Before sensitive operations such as changing the email address, phone number or MFA settings.

Glossary

Term Meaning, with an example
API Application programming interface: a fixed way for one program to ask another for something, e.g. the shop app asking the server for an order.
Endpoint One thing an API offers: an address plus an action, e.g. GET /api/orders/501.
Request / response What the caller sends / what comes back, e.g. GET /api/orders/501 and the order's JSON.
JSON A text format of names and values, e.g. {"name": "Ravi"}.
HTTP method The action in a request: GET, POST, PUT, PATCH, DELETE (episode 21).
REST An API style with one URL per resource plus HTTP methods, e.g. PATCH /api/users/me.
Resource A thing a REST API exposes at a URL, e.g. one order.
GraphQL A query language for APIs: usually one URL, and the client names the fields it wants, e.g. { order(id: 502) { item } }.
GraphQL query / mutation A request that reads data / a request that changes it.
gRPC A remote procedure call system: call a method on a server as if it were local, e.g. GetOrder(OrderRequest).
Remote procedure call (RPC) Calling a function that runs on another machine.
Protocol Buffers gRPC's default typed message format, defined in advance.
Attack surface Every place an attacker can try to get in: every door, endpoint, version, parameter and field.
REST, GraphQL and gRPC attack surface Each API style is another door into the same data, and each needs the same checks.
OWASP Open Worldwide Application Security Project: a community that publishes free security guidance (episode 36).
OWASP API Security Top 10 2023 OWASP's list of the ten most common API risks, second edition (the first was 2019).
Authentication Proving who you are (episode 28).
Authorization Deciding what an identified user may do (episode 30).
Object One stored record, e.g. order 501.
Object ID The number or code that names an object, e.g. 501.
API1 BOLA Broken Object Level Authorization: an object is returned or changed without checking the caller may access it.
IDOR Insecure direct object reference: the web-app name for BOLA (episode 37).
Object-level check "Can this user do this action on this record?", asked for every client-supplied ID.
404 Not Found HTTP status for "no such thing", also used for "not yours" so nothing leaks.
UUID / GUID A 128-bit random identifier, which is hard to guess but is not access control.
API2 Broken Authentication Weak or wrongly implemented proof of identity, e.g. accepting unsigned tokens.
Token A string sent with each request that proves who the caller is.
Bearer token A token that works for whoever holds it (episode 31).
JWT JSON Web Token: a signed token with claims such as sub and exp (episode 31).
Base64 An encoding that anyone can reverse. It is not encryption (episode 10).
Signature / HMAC Proof that the server made the token. An HMAC is a keyed hash computed with a secret (episode 12).
Expiry (exp) The time after which a token stops working.
Constant-time comparison A comparison that takes the same time wherever two values differ, e.g. hmac.compare_digest.
401 Unauthorized HTTP status for "who are you?": missing, bad or expired credentials.
API key A long-lived string that names a program or project, used for quotas and billing, not for users.
API keys vs tokens A key says which app is calling; a user token says which user, is short-lived and has scopes.
Scopes The permissions a token carries, e.g. orders:read (episode 32).
Re-authentication Asking for the password or MFA again before a sensitive change.
MFA Multi-factor authentication (episode 29).
Credential stuffing Trying username/password pairs leaked from other sites (episode 48).
Microservice A small service that talks to other services, usually over an API.
Property One named field of an object, e.g. email.
API3 BOPLA Broken Object Property Level Authorization: missing checks on reading or writing individual fields.
Serialisation Turning an object into text such as JSON, e.g. json.dumps(user).
Excessive data exposure Sending fields the reader shouldn't see, e.g. a password hash in a public profile.
DTO Data transfer object: a structure holding only the fields one request or response may carry.
Response DTO The allowlist of fields that may go out, e.g. name, city.
Response filtering with DTOs Building every response from a DTO instead of the internal object.
Mass assignment Copying every request field into the stored object, e.g. "is_admin": true.
Auto-binding A framework copying request fields into object fields automatically.
Update DTO The allowlist of fields (and their types) a user may change.
Allowlist A list of what's permitted. Everything else is refused (episode 36).
400 Bad Request HTTP status for a request refused as malformed or not allowed.
Schema A written description of every field and its type.
Field-level authorization Checking permission for each field, which is essential in GraphQL.
Fail closed Refusing when something is missing or unclear, e.g. a token with no expiry.

Sources

Fetched on 12 Nov 2026:

  • OWASP API Security Top 10 2023, overview: https://api-security.owasp.org/editions/2023/en/0x11-t10/
  • Release notes (second edition, four years after 2019; the API3 merge): https://owasp.org/API-Security/editions/2023/en/0x04-release-notes/
  • API1:2023 Broken Object Level Authorization: https://owasp.org/API-Security/editions/2023/en/0xa1-broken-object-level-authorization/
  • API2:2023 Broken Authentication: https://api-security.owasp.org/editions/2023/en/0xa2-broken-authentication/
  • API3:2023 Broken Object Property Level Authorization: https://api-security.owasp.org/editions/2023/en/0xa3-broken-object-property-level-authorization/
  • GraphQL introduction: https://graphql.org/learn/introduction/
  • gRPC introduction: https://grpc.io/docs/what-is-grpc/introduction/

Summary

  • An API is a door into your data, and REST, GraphQL and gRPC are three kinds of door. Put every check at the data, so every door runs it.
  • The OWASP API Security Top 10 2023 lists the ten most common API risks. API1 to API3 are about authorization and authentication.
  • API1 BOLA: check ownership of every object ID the client sends, answer 404, and test user A against user B. Random IDs help but are not the check.
  • API2 Broken authentication: verify each token's signature and then its expiry, use well-tested libraries, and remember that API keys name programs, not people.
  • API3 BOPLA: data goes out only through a response DTO and comes in only through an update DTO allowlist. In GraphQL, authorize every field.

Next episode: API security part 2: the OWASP API Security Top 10 (2023), items 4 to 10.