liveBook · Manning

Middleware

As explained in Secure APIs

Middleware is software that intercepts and processes requests or responses between a client and an application endpoint.

Middleware is a request-processing layer between a client and an API endpoint. It can inspect headers, validate access information, apply business rules, and return an error before the endpoint handles the request. section 4.10 section 8.7

A practical use is protecting a ticket checkout flow from scalping bots. Middleware checks for an allowed browser user agent, obtains the user identity from access-token claims, and rejects a purchase when that user bought a ticket within the previous 24 hours. section 4.10

The example applies these decisions:

  • Return 401 Unauthorized when the request does not contain an allowed browser user agent. section 4.10
  • Return 409 Conflict when the authenticated user has a recent transaction. section 4.10
  • Keep the rule aligned with the application’s business requirements rather than treating middleware as a universal defense. section 4.10
Listing 4.14 Custom middleware to prevent scalping
# file: ch04/vulnerable_business_flows.py
class UserClaims(BaseModel):
    sub: str

def validate_access():     #1
    return UserClaims(
        sub="deb6f47e-fd9d-4b4c-ae4f-c85726ed502c"
    )

@server.middleware("http.request")     #2
async def prevent_scalping(request: Request, call_next):
    if not any(     #3
        agent in request.headers["user-agent"] for agent in allowed_agents
    ):
        return JSONResponse(     #4
            status_code=401, content={"error": "Unauthorized"}
        )

    user_claims = validate_access()     #5


    if request.url.path == "/checkout":     #6
        for transaction in recent_transactions:
            if (     #7
                transaction.sub == user_claims.sub
                and transaction.within_24h
            ):
                return JSONResponse(     #8
                    status_code=409, content={"error": "Conflict"}
                )
    return await call_next(request)    #9

Inspect the focused middleware example to see request-header inspection, access validation, path matching, transaction lookup, and JSON error responses. section 4.10

How Secure APIs covers it

How deep it goes
Demonstrates implementation through a ticketing example but acknowledges that the mitigation only scratches the surface of abuse prevention.
Examples
Uses ticket checkout, allowed user agents, authenticated user claims, and 24-hour transaction records as concrete artifacts.
What it assumes
Assumes access-token validation and user claims while connecting middleware to broader authentication and authorization implementation.
What you can do after
Build custom request middleware that rejects unauthorized clients and prevents repeated purchases according to application rules.
How it connects
Connects request handling with access tokens, authentication, authorization, role-based access control, and business requirements.

Also explained in

Compare how 10 books explain middleware →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secure APIs. The section links point to the parts of the book it draws on.