Course outline

FastAPI / Basic: HTTP and typed boundaries / Lesson 7

Request headers and cookies

Declare header and cookie inputs, test their absence and avoid trusting client-controlled metadata.

About 21 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Distinguish header, cookie and query inputs.
  • Declare optional and required request metadata.
  • Test parsing and avoid exposing credentials.
  • Extract and validate headers and cookies at the HTTP boundary.
  • Separate client-controlled metadata from trusted authentication and authorization.

Choose the input location

HTTP headers and cookies carry metadata alongside a request; neither is trusted merely because it arrives outside the JSON body. FastAPI uses explicit Header and Cookie declarations to distinguish these values from query parameters. Decide whether each value is required, what shape is accepted and how it affects the operation. Authentication and authorization need their own validated security design rather than a client-supplied identity header.

Declare a header

The example declares an optional X-Request-Id header. By default FastAPI converts underscores in the Python parameter name to hyphens for header extraction, so the client sends X-Request-Id. Treat a caller-provided correlation value as untrusted: validate its length and characters or generate your own, and do not use it as proof of identity. Header names are case-insensitive under HTTP semantics.

python Read an optional request identifier
from typing import Annotated
from fastapi import FastAPI, Header

app = FastAPI()

@app.get('/trace')
def trace(x_request_id: Annotated[str | None, Header()] = None):
    return {'request_id': x_request_id}

The returned value is synthetic and must be validated before use in production logs.

The second example reads an optional preference cookie. It is an input to the application, not proof that a user has permission to access an object. A real session or authentication cookie requires secure lifecycle, appropriate flags and server-side validation. Do not return session values in a public response or put them into logs. The synthetic preference in the example is deliberately nonsecret.

python Read an optional nonsecret preference cookie
from typing import Annotated
from fastapi import Cookie, FastAPI

app = FastAPI()

@app.get('/preference')
def preference(theme: Annotated[str | None, Cookie()] = None):
    return {'theme': theme}

The preference is not authentication. The application must validate any value before using it.

Test absence and malformed input

Send requests with and without each optional value and inspect both response and OpenAPI description. For a required header or cookie, test its absence and an invalid value separately; inspect the validation error location without exposing sensitive values. If an upstream proxy modifies headers, reproduce the request through that proxy as a separate integration case. A local test client does not prove deployed header forwarding.

Separate metadata and security

Use a server-owned principal established by an appropriate security dependency for access decisions. Correlation identifiers can connect safe logs across services, but accepting arbitrary strings without limits can pollute logs or increase cardinality. Test an attacker-controlled identity-like header against a protected synthetic record and confirm it cannot grant access. Set cookie behavior according to the application’s HTTPS, cross-site and session requirements.

Declare request metadata at its actual source

Headers and cookies carry client-supplied request metadata outside the path, query, and JSON body. FastAPI can extract a header through Header and a cookie through Cookie; with Annotated, the Python type and source metadata stay together in the function signature. A required header or cookie without a default must be supplied, while a default such as None permits omission. Test a real request through an isolated client: directly calling the handler does not demonstrate how HTTP metadata is extracted or validated.

A header name is case-insensitive in HTTP. FastAPI normally maps underscores in a Python header parameter to hyphens, so x_request_id reads X-Request-Id. This conversion is specific to Header declarations and can be customized; an explicit alias changes the public name clients must send. Inspect the generated schema and send the documented spelling in tests. Avoid assuming a Python identifier is the literal wire name, and consider proxy rules before disabling underscore conversion because some intermediaries reject underscore-containing names.

Design behavior for repeated headers

HTTP requests can contain repeated header fields. FastAPI supports declaring a list-valued Header to collect duplicate values, but intermediaries may combine, reorder, reject, or otherwise transform fields according to their own configuration and the field’s semantics. A comma inside one field is not automatically equivalent to two independent header lines for every application contract. Decide what a specific header means, test the actual client and proxy boundary, and avoid relying on an accidental first-or-last choice for security-sensitive metadata.

If an application requires exactly one request identifier, explicitly validate the count before using it and reject ambiguous input under a documented policy. Do not treat an untrusted request identifier as a verified identity or authorization claim. Generate or replace a correlation identifier at a trusted boundary when needed, limit its length and allowed characters, and avoid putting credentials or arbitrary header content into logs. These application policies are separate from FastAPI merely extracting a value.

Separate client cookies from server trust

Cookie declares a named value from the incoming Cookie header. A preference such as theme=dark can customize a presentation, but the client controls the value and may omit or alter it. It does not by itself establish identity, ownership, or permission to download a file. If a cookie carries a session token, the application must validate it through an appropriate server-side or cryptographic design, check its expiry and revocation as applicable, and authorize the requested operation independently. Never log raw session tokens or return them in debugging responses.

Response.set_cookie sends a Set-Cookie response header that instructs a compatible client to store a cookie; Cookie reads a cookie subsequently sent in a request. These are different directions of the exchange. Cookie options such as Secure, HttpOnly, SameSite, path, and domain affect browser behavior, but do not replace server-side validation or authorization. Choose options for the actual deployment and cross-site requirements, use HTTPS where Secure is expected, and test the browser and proxy behavior separately from a local in-process client.

Validate absence, shape, and policy independently

A header or cookie annotation can describe a string or another supported type and constraints such as length. A missing required input produces a request-validation error, while an optional value with a default can reach the handler as None. Empty text and an absent field are distinct cases; test both when the contract depends on that distinction. Explicit aliases should be tested with the public name rather than only a Python keyword. Do not assume successful parsing proves that a request ID is unique, a cookie is authentic, or a principal may access a resource.

Different systems can place limits on header and cookie size before FastAPI receives a request. An application field constraint is not a total transport-size limit and cannot guarantee how every proxy rejects oversized data. Apply separate deployment controls and avoid using user-controlled metadata as a filesystem path, SQL fragment, or unrestricted log line. When returning a validation error, avoid copying sensitive cookie values or Authorization headers into the public response or unreviewed logs.

Exercise the HTTP exchange and its limits

Use TestClient with synthetic headers and cookies to test a valid input, missing required metadata, an optional omission, an alias, and duplicate fields. Inspect status and relevant response fields, not merely the handler’s local argument. When testing a cookie-setting route, inspect Set-Cookie attributes and then issue a follow-up request with the client’s cookie handling; use an isolated browser-level test when browser-specific enforcement matters. Keep example tokens obviously synthetic and do not point tests at a real account or service.

For an authorization test, seed a synthetic protected object, authenticate a principal through the intended verifier or a narrowly scoped test override, and check access independently of a preference cookie. A valid preference may alter display but must not grant download access. Test both an allowed principal and a denied principal, and check that rejected requests do not read or return protected content. In-process tests do not establish production proxy normalization, cookie storage policy, TLS, or cross-site browser behavior. The following fragments are illustrative and assume their stated app and imports.

20 worked examples

1. Default header spelling

Problem: Trace a hyphenated header to a Python parameter.

  1. Header converts the Python underscores to hyphens by default.
  2. The supplied header value is injected into x_request_id.
python Default header spelling
@app.get("/trace")
def trace(x_request_id: Annotated[str, Header()]):
    return {"id": x_request_id}
# GET /trace; X-Request-Id: req-7 -> {"id":"req-7"}

Illustrative isolated FastAPI fragment or synthetic trace; imports and fixtures are assumed.

Expected result: The response contains id req-7.

Why this result follows: Header metadata maps the parameter to its HTTP header name.

2. Case-insensitive header name

Problem: Send the same header using lowercase letters.

  1. HTTP header names are case-insensitive.
  2. The lowercase wire name matches the declared X-Request-Id header.
python Case-insensitive header name
@app.get("/trace")
def trace(x_request_id: Annotated[str, Header()]): return {"id":x_request_id}
# GET /trace; x-request-id: req-8 -> {"id":"req-8"}

Illustrative isolated FastAPI fragment or synthetic trace; imports and fixtures are assumed.

Expected result: The response contains id req-8.

Why this result follows: Header name matching does not depend on letter case.

3. Missing required header

Problem: Predict validation when required metadata is absent.

  1. The Header declaration has no default and is required.
  2. The request does not supply the expected header, so validation rejects it.
python Missing required header
@app.get("/trace")
def trace(x_request_id: Annotated[str, Header()]): return {"id":x_request_id}
# GET /trace without X-Request-Id -> 422

Illustrative isolated FastAPI fragment or synthetic trace; imports and fixtures are assumed.

Expected result: The response status is 422.

Why this result follows: Required header extraction occurs before the handler runs.

4. Optional header omission

Problem: Allow a request identifier to be absent.

  1. The parameter has an explicit None default.
  2. When the header is absent the handler receives None.
python Optional header omission
@app.get("/trace")
def trace(x_request_id: Annotated[str | None, Header()] = None):
    return {"id":x_request_id}
# GET /trace without header -> {"id":null}

Illustrative isolated FastAPI fragment or synthetic trace; imports and fixtures are assumed.

Expected result: The response contains id as JSON null.

Why this result follows: The default makes the header omittable.

5. Explicit header alias

Problem: Publish a chosen wire name for a Python variable.

  1. The alias explicitly names X-Correlation-ID on the wire.
  2. FastAPI injects that value into the Python variable request_id.
python Explicit header alias
@app.get("/trace")
def trace(request_id: Annotated[str, Header(alias="X-Correlation-ID")]):
    return {"id":request_id}
# X-Correlation-ID: corr-2 -> {"id":"corr-2"}

Illustrative isolated FastAPI fragment or synthetic trace; imports and fixtures are assumed.

Expected result: The response contains id corr-2.

Why this result follows: The explicit alias defines the public header name.

6. Constrained header length

Problem: Reject an excessively long synthetic identifier.

  1. The request supplies nine characters in the declared header.
  2. The field constraint permits at most eight characters and rejects the value.
python Constrained header length
@app.get("/trace")
def trace(x_request_id: Annotated[str, Header(max_length=8)]): return {"id":x_request_id}
# X-Request-Id: abcdefghi -> 422

Illustrative isolated FastAPI fragment or synthetic trace; imports and fixtures are assumed.

Expected result: The response is 422 before the handler result.

Why this result follows: Header constraints validate the extracted field value.

7. Empty versus absent

Problem: Distinguish a missing header from empty text.

  1. The header is present but its string value has length zero.
  2. The minimum-length rule rejects that empty value.
python Empty versus absent
@app.get("/trace")
def trace(x_request_id: Annotated[str, Header(min_length=1)]): return {"id":x_request_id}
# X-Request-Id: (empty) -> 422

Illustrative isolated FastAPI fragment or synthetic trace; imports and fixtures are assumed.

Expected result: The response is 422 for the empty header.

Why this result follows: Presence alone does not satisfy a nonempty constraint.

8. Repeated header list

Problem: Collect duplicate synthetic tag headers.

  1. The list-valued Header declaration accepts repeated occurrences.
  2. Both supplied field values are made available to the handler as a list.
python Repeated header list
@app.get("/tags")
def tags(x_tag: Annotated[list[str], Header()]): return {"tags":x_tag}
# request headers: X-Tag: red; X-Tag: blue
# response contains both red and blue

Illustrative isolated FastAPI fragment or synthetic trace; imports and fixtures are assumed.

Expected result: The response list contains red and blue.

Why this result follows: A list header parameter can capture duplicate header values.

9. Reject ambiguous identifiers

Problem: Enforce one correlation header explicitly.

  1. The list declaration makes the two occurrences visible to the application.
  2. The policy rejects a count other than one instead of choosing one implicitly.
python Reject ambiguous identifiers
@app.get("/trace")
def trace(x_request_id: Annotated[list[str], Header()]):
    if len(x_request_id) != 1: raise HTTPException(status_code=400, detail="one ID required")
    return {"id":x_request_id[0]}
# two X-Request-Id fields -> 400

Illustrative isolated FastAPI fragment or synthetic trace; imports and fixtures are assumed.

Expected result: The fixture returns 400 with detail one ID required.

Why this result follows: An explicit count rule resolves ambiguous repeated metadata.

10. Read a preference cookie

Problem: Extract a client-supplied display preference.

  1. Cookie identifies theme as an incoming cookie value.
  2. The handler returns the synthetic display preference sent by the client.
python Read a preference cookie
@app.get("/view")
def view(theme: Annotated[str | None, Cookie()] = None): return {"theme":theme}
# Cookie: theme=dark -> {"theme":"dark"}

Illustrative isolated FastAPI fragment or synthetic trace; imports and fixtures are assumed.

Expected result: The response contains theme dark.

Why this result follows: Cookie metadata extracts the named request cookie.

11. Missing optional cookie

Problem: Use a default when a preference is absent.

  1. The request sends no theme cookie.
  2. The explicit None default is passed to the handler.
python Missing optional cookie
@app.get("/view")
def view(theme: Annotated[str | None, Cookie()] = None): return {"theme":theme}
# GET /view without Cookie -> {"theme":null}

Illustrative isolated FastAPI fragment or synthetic trace; imports and fixtures are assumed.

Expected result: The JSON response contains theme null.

Why this result follows: An optional cookie can be omitted under the declared default.

12. Required cookie

Problem: Reject an absent required cookie field.

  1. The cookie parameter has no default.
  2. The request lacks the required cookie, so validation does not call the handler.
python Required cookie
@app.get("/view")
def view(theme: Annotated[str, Cookie()]): return {"theme":theme}
# GET /view without theme -> 422

Illustrative isolated FastAPI fragment or synthetic trace; imports and fixtures are assumed.

Expected result: The response status is 422.

Why this result follows: A required Cookie declaration enforces presence.

13. Set and read a cookie

Problem: Trace the two directions of a cookie exchange.

  1. The handler adds Set-Cookie to the outgoing response.
  2. A compatible client may store it and send theme in a later Cookie request header.
python Set and read a cookie
@app.post("/theme")
def set_theme(response: Response):
    response.set_cookie(key="theme", value="dark", httponly=True)
    return {"ok":True}
# response includes Set-Cookie for theme=dark; HttpOnly

Illustrative isolated FastAPI fragment or synthetic trace; imports and fixtures are assumed.

Expected result: The response sets the synthetic dark preference with HttpOnly.

Why this result follows: Setting a response cookie and reading a later request cookie are separate steps.

14. Cookie is not authorization

Problem: Deny a download despite a favorable preference.

  1. The theme cookie is a client-controlled display preference.
  2. The verified principal differs from the protected file owner.
text Cookie is not authorization
request cookie: theme=dark
verified principal: user-8
file owner: user-7
owner-only policy result: deny

Illustrative isolated FastAPI fragment or synthetic trace; imports and fixtures are assumed.

Expected result: The download is denied under the stated owner-only policy.

Why this result follows: Authorization checks the principal and target rather than a preference.

15. Synthetic session verification

Problem: Use a cookie only after server verification.

  1. The server resolves the token to an active trusted principal in this fixture.
  2. The application separately compares that principal with the requested file owner.
text Synthetic session verification
session cookie: synthetic-token
server session store: synthetic-token -> user-7, active
requested file owner: user-7
policy result: allow

Illustrative isolated FastAPI fragment or synthetic trace; imports and fixtures are assumed.

Expected result: The synthetic request is allowed by the owner-only policy.

Why this result follows: A verified session and a resource policy provide distinct checks.

16. Expired session

Problem: Reject a token that no longer represents an active session.

  1. The client sends a cookie but the server-side fixture marks its session expired.
  2. The application does not treat the raw token as an authenticated principal.
text Expired session
session cookie: synthetic-expired
server session store: synthetic-expired -> expired
protected download: denied

Illustrative isolated FastAPI fragment or synthetic trace; imports and fixtures are assumed.

Expected result: The protected download is denied.

Why this result follows: Cookie presence alone does not establish a valid session.

17. Cookie alias

Problem: Read a public cookie name different from Python identifier.

  1. The Cookie alias specifies theme as the incoming cookie name.
  2. The extracted value is passed into display_theme.
python Cookie alias
@app.get("/view")
def view(display_theme: Annotated[str | None, Cookie(alias="theme")] = None):
    return {"theme":display_theme}
# Cookie: theme=light -> {"theme":"light"}

Illustrative isolated FastAPI fragment or synthetic trace; imports and fixtures are assumed.

Expected result: The response contains theme light.

Why this result follows: The alias separates the wire name from the Python variable.

18. Cookie attributes

Problem: Inspect storage directives in a synthetic response.

  1. The server sends directives describing how a compatible browser should handle the cookie.
  2. These flags do not themselves verify the session or authorize access.
python Cookie attributes
response.set_cookie(key="session", value="synthetic", secure=True, httponly=True, samesite="lax")
# Set-Cookie includes Secure; HttpOnly; SameSite=lax

Illustrative isolated FastAPI fragment or synthetic trace; imports and fixtures are assumed.

Expected result: Set-Cookie includes Secure, HttpOnly, and SameSite=lax.

Why this result follows: Cookie attributes affect client handling, not server trust decisions.

19. Avoid logging credentials

Problem: Select safe metadata for a request log.

  1. The request ID is an approved synthetic correlation value in this fixture.
  2. The Authorization header carries a credential and is excluded from the log.
text Avoid logging credentials
incoming headers: Authorization: Bearer synthetic-secret; X-Request-Id: req-4
log: {"request_id":"req-4", "event":"received"}
Authorization value: omitted

Illustrative isolated FastAPI fragment or synthetic trace; imports and fixtures are assumed.

Expected result: The log contains req-4 and no synthetic-secret.

Why this result follows: Allowlisting log fields avoids copying credential-bearing headers.

20. Proxy normalization boundary

Problem: Explain an in-process test that misses proxy behavior.

  1. The local client sends the normal hyphenated header directly to the application.
  2. The proxy’s separate handling of underscore names is not exercised by that request.
text Proxy normalization boundary
TestClient -> app: X-Request-Id: req-5 -> 200
proxy configuration: rejects a differently named underscore header
production path: proxy -> app

Illustrative isolated FastAPI fragment or synthetic trace; imports and fixtures are assumed.

Expected result: The local success does not establish the proxy policy.

Why this result follows: In-process extraction and intermediary behavior are different test boundaries.

Common errors and fixes

A header appears missing

Why it happens
The client sent a query parameter or used the wrong header name.
How to fix it
Declare Header and send the documented hyphenated name.
Prevent it next time
Test the actual wire request and generated schema.

A client identity header grants access

Why it happens
Untrusted metadata was treated as authenticated identity.
How to fix it
Authenticate the principal and authorize the object.
Prevent it next time
Test a forged header against a protected record.

A session value appears in logs

Why it happens
Cookie contents were recorded as diagnostic metadata.
How to fix it
Remove the secret from logs and rotate it if exposure occurred.
Prevent it next time
Use safe correlation identifiers and logging tests.

20 practice exercises

1. The Python parameter is x_request_id. Which default HTTP header should a client send?

Show hint

Apply Header’s default underscore-to-hyphen conversion.

Show worked solution

Send X-Request-Id. FastAPI converts underscores to hyphens by default for Header. Test the actual request and schema, especially if custom aliases or proxy rules are used.

Send X-Request-Id for the Python parameter x_request_id under the default Header behavior. HTTP header names are case-insensitive; test the public spelling and schema again if an alias or proxy policy changes.

Check your solution

  • The request sends X-Request-Id.
  • The handler receives the synthetic identifier.

2. Can a preference cookie authorize a download?

Show hint

Separate display preference from authenticated identity and object permission.

Show worked solution

No. A client controls the cookie value unless the application validates it under an appropriate security design. Authenticate the principal and check permission for the requested object before serving the file.

No: a preference cookie is client-controlled and does not authorize a file download. Authenticate the principal through a trusted verifier, load the requested file, and apply the relevant permission policy before serving its contents.

Check your solution

  • The preference cookie alone grants no download.
  • The verified principal is checked against the requested file.

3. A client sends X-Request-Id in two different letter cases. Design a route test showing both reach x_request_id and documenting the public spelling.

Show hint

HTTP header names are case-insensitive.

Show worked solution

Declare x_request_id with Header and send separate requests using X-Request-Id and x-request-id with distinct values. Assert each value reaches the handler and inspect the generated schema for the public header name.

Check your solution

  • Both header spellings reach the same parameter.
  • The schema records the intended public name.

4. A route requires both X-Request-Id and a session cookie. Design a test for a request missing both, plus a valid control.

Show hint

Validation locations identify distinct input sources.

Show worked solution

Send a request without the header or cookie and assert 422 with locations for both, and no handler call. Send both synthetic values in a control request and assert the handler is reached; authentication of the cookie remains a separate policy.

Check your solution

  • Both missing input locations are reported.
  • The valid control reaches the handler.

5. An optional X-Request-Id is omitted in one request and explicitly empty in another. Design tests that distinguish the values under a contract allowing empty strings.

Show hint

None and an empty string are different values.

Show worked solution

Declare the optional header with default None and no minimum-length constraint. Assert omission gives JSON null while an explicitly empty header gives an empty string; document whether the application accepts that latter value.

Check your solution

  • Omission yields null.
  • An empty header yields an empty string.

6. A header is renamed from X-Old-ID to X-New-ID during a transition. Define behavior when both are supplied with conflicting values and design tests.

Show hint

A single alias does not define conflict handling.

Show worked solution

Accept both headers explicitly during the documented transition and reject conflicts or specify deterministic precedence. Test old-only, new-only, matching, and conflicting values, then remove the old name only after clients migrate.

Check your solution

  • Both individual names follow the transition contract.
  • Conflicting values have a documented tested outcome.

7. A request ID must contain 1–8 characters. Design tests for missing, empty, exact-limit and over-limit values and confirm rejection precedes the handler.

Show hint

Presence and length are distinct constraints.

Show worked solution

Use a required Header with min_length=1 and max_length=8. Assert missing, empty and nine-character values return 422 without handler calls, while an eight-character value succeeds and is recorded once.

Check your solution

  • Invalid inputs do not reach the handler.
  • The eight-character control reaches the handler.

8. A request includes a header that is present but blank. A custom error response should distinguish it from omission without echoing the submitted value. Design tests.

Show hint

Inspect safe error categories or locations.

Show worked solution

Apply a nonempty header constraint and send an empty field and a request with no field. Assert both are rejected, the documented classifications distinguish empty from missing, and neither response or sanitized log copies submitted sensitive data.

Check your solution

  • Both empty and missing inputs are rejected.
  • The safe error contract distinguishes their causes.

9. A proxy may combine repeated X-Tag fields before forwarding. Design an isolated test comparing what the app receives directly and through the intended proxy.

Show hint

The intermediary can change the header representation.

Show worked solution

Send identical repeated synthetic fields directly and through the configured proxy, and record the list observed by the app in each case. Assert the documented proxy contract and avoid assuming comma-combined values are automatically split into separate tags.

Check your solution

  • The direct and proxied representations are observed separately.
  • The result is checked against the documented proxy policy.

10. A security-sensitive request ID must occur exactly once. Design tests for zero, one, and two header occurrences without silently choosing a duplicate.

Show hint

Check cardinality explicitly.

Show worked solution

Receive the values as a list and enforce the documented exactly-one rule. Assert an omitted field and two occurrences are rejected, while one value is accepted and used as the identifier; test proxy transformations separately.

Check your solution

  • Zero and two occurrences are rejected.
  • Exactly one occurrence is accepted.

11. A preference endpoint reads optional theme and language cookies. Design a test that supplies one and omits the other, then verifies the resulting response.

Show hint

Each cookie has its own optional default.

Show worked solution

Declare both cookies optional with explicit None defaults. Send only theme=dark, assert theme is dark and language is null, then send both in a control. Treat both values as untrusted preferences, not identity.

Check your solution

  • One supplied cookie is extracted and the omitted cookie is null.
  • The two-cookie control supplies both values.

12. A required session cookie is missing, and the handler would write an audit row on success. Design a test proving validation stops the write and a control reaches it.

Show hint

Check the side effect as well as the status.

Show worked solution

Send a request with no cookie and assert 422 with a cookie location and no audit write. In an isolated fixture supply a syntactically valid synthetic cookie and assert the handler runs, while treating authentication verification as a separate boundary.

Check your solution

  • The missing cookie causes no write.
  • The supplied-cookie control reaches the handler.

13. A test client receives Set-Cookie for a preference, then requests a second route. Design an integration test proving the later route receives the stored value.

Show hint

Set-Cookie is a response header; Cookie is sent later by the client.

Show worked solution

Within one isolated TestClient session, call the setter and inspect Set-Cookie, then call the reader and assert it returns the preference. Use a fresh client as a no-cookie control and avoid claiming browser enforcement of cookie attributes from this test.

Check your solution

  • The second request in the same client receives the preference.
  • A fresh client follows the no-cookie behavior.

14. A preference cookie requests dark mode, and the session belongs to user 8 while a file belongs to user 7. Design a denial test and an owner control.

Show hint

Display preference and resource authorization are separate.

Show worked solution

Keep the real owner policy active, supply synthetic sessions for user 8 and user 7, and request the same file. Assert the non-owner receives the documented denial with no file bytes while the owner succeeds; the theme must not change either decision.

Check your solution

  • The non-owner receives no protected file.
  • The owner succeeds independently of theme.

15. A session cookie verifies successfully but its account is disabled before a protected download. Design a test for the additional decision and a valid control.

Show hint

A valid token is not the entire authorization decision.

Show worked solution

Use a fake session verifier and account store while retaining the real access policy. Assert the disabled account is denied and no protected bytes are returned, then use an active authorized account as a control.

Check your solution

  • The disabled account cannot download the file.
  • The active authorized control succeeds.

16. A session was valid for a first request but is revoked before a second. Design a test proving the server rechecks trusted session state.

Show hint

The client can continue sending the same cookie after revocation.

Show worked solution

Have a fake session store mark the synthetic token active for the first request and revoked for the second. Assert the first authorized operation succeeds, the second receives the documented denial, and no second protected action occurs.

Check your solution

  • The first request succeeds while the session is active.
  • The revoked second request performs no protected action.

17. A cookie was renamed from display_theme to theme. Design a transition test for requests containing old, new, and conflicting values.

Show hint

An alias alone does not establish precedence between two cookies.

Show worked solution

During a documented transition read both names explicitly and reject conflicting values or define deterministic precedence. Test old-only, new-only, equal, and conflicting requests, and remove the old name after clients migrate.

Check your solution

  • Both individual names follow the transition policy.
  • A conflict has a documented tested result.

18. A response sets Secure, HttpOnly, and SameSite=lax. Explain what those attributes do not prove.

Show hint

Browser handling is separate from server authorization.

Show worked solution

The attributes instruct compatible clients how to handle the cookie; they do not validate a session or grant access. Test actual browser and deployment behavior and enforce server-side authentication and policy.

Check your solution

  • Cookie flags do not replace session validation.
  • Authorization remains a server-side check.

19. A request contains a session cookie, an Authorization header, and a request ID. Design a structured diagnostic and redaction test across all three.

Show hint

Allowlist correlation fields instead of copying headers.

Show worked solution

Record an approved event and bounded request ID, omitting both the cookie and Authorization values. Submit distinct synthetic secrets in each credential source and assert neither appears in captured logs or public errors.

Check your solution

  • The event and request ID remain useful.
  • Neither synthetic credential appears in either output.

20. An app-only header test passes, but a proxy drops duplicate request IDs. Design a deployment-level test that detects this change and checks the application policy.

Show hint

Exercise the actual intermediary boundary in isolation.

Show worked solution

Send zero, one, and two synthetic request-ID occurrences through the intended proxy and observe what reaches the app. Assert the documented exactly-one policy after transformation and record whether the proxy rejects, preserves, or combines duplicates.

Check your solution

  • The test measures what the proxy forwards.
  • The resulting application behavior matches the documented policy.

Key takeaways

  • Headers and cookies are explicit, client-controlled input locations.
  • Authentication, authorization and safe logging remain separate responsibilities.
  • Header underscores normally map to hyphens on the wire.
  • Cookie values are client-supplied and need an explicit trust design.
  • Test duplicates, omission, and actual proxy or browser behavior separately.

Official references