Session Fixation in Fastapi
How Session Fixation Manifests in Fastapi
Session fixation in Fastapi occurs when an application accepts an attacker-supplied session identifier and then authenticates a user against it, without forcing a new identifier after login. Fastapi does not manage sessions by itself; the risk arises from how session identifiers are created, stored, and validated when integrating with frameworks like OAuth2 with password flow, or when using cookies via middleware such as Starlette’s SessionMiddleware or custom cookie-based tokens.
Concrete Fastapi-specific patterns include:
- Setting a session cookie (e.g.,
session_id) before authentication and retaining it after login, allowing an attacker to craft a URL with a known session token and trick a victim into authenticating under that token. - Using a predictable or static identifier (e.g., a user-provided username or a non-random value) as the session key, which makes token guessing feasible.
- Failure to rotate the session token on privilege change, such as after multi-factor authentication or role elevation, enabling horizontal privilege escalation via BOLA/IDOR-like paths where one user can reuse another’s session.
- Exposing session identifiers in URLs or logs, which can lead to leakage via Referer headers or browser history.
In Fastapi, these issues often surface in routes that handle login while reusing an incoming cookie or query parameter as the session key. For example, an endpoint that reads request.cookies.get("session_id") before authentication and then writes the authenticated user into that same cookie without regeneration creates a fixation surface. Similarly, OAuth2 password flow implementations that store the session token in a cookie set by the client prior to token issuance can be abused to force a victim’s session identifier.
Fastapi-Specific Detection
Detecting session fixation in Fastapi requires analyzing how session identifiers are assigned, validated, and rotated across authenticated and unauthenticated paths. Because Fastapi is unopinionated about sessions, you must inspect integration points such as Starlette middleware, custom dependencies, and token handling logic.
Indicators of risk include:
- A login route that accepts or reuses a client-supplied session cookie or token without issuing a new identifier upon successful authentication.
- Session identifiers that are not cryptographically random or lack sufficient entropy (e.g., derived from user IDs, timestamps, or nonces without secure randomization).
- Missing
HttpOnly,Secure, andSameSiteattributes on session cookies, or absence of strict cookie scope configuration. - Endpoints that mutate privilege levels without reissuing the session token, enabling token reuse across authentication states.
With middleBrick, you can scan a Fastapi service to surface these patterns as part of its unauthenticated attack surface testing. The tool performs 12 security checks in parallel, including Authentication, BOLA/IDOR, and Unsafe Consumption, which can highlight endpoints where session identifiers are accepted from untrusted sources or not rotated after login. Its OpenAPI/Swagger analysis resolves $ref definitions and cross-references spec definitions with runtime findings, helping you map session handling routes against the specification. The LLM/AI Security checks do not apply here, but the scanner’s rate limiting and data exposure checks can indirectly indicate whether session tokens are exposed in logs or responses.
To scan with middleBrick from the terminal, use the CLI:
middlebrick scan https://api.example.com/openapi.json
In the Web Dashboard, review the per-category breakdowns and prioritized findings; in the CLI, use JSON output for scripting:
middlebrick scan https://api.example.com/openapi.json --output jsonFastapi-Specific Remediation
Remediation in Fastapi focuses on ensuring that session identifiers are created securely after authentication and rotated whenever trust boundaries change. Use server-side session stores and cryptographically random tokens, and enforce strict cookie attributes.
Key practices and code examples:
- Generate a new session token upon successful authentication using
secrets.token_urlsafeoros.urandom, and store it server-side (e.g., in Redis) with a mapping to the user ID. - Never reuse a client-supplied identifier for an authenticated session. If a cookie is provided before login, discard it after successful authentication and issue a new one.
- Set secure cookie attributes:
HttpOnly,Secure(in production), andSameSite=LaxorStrictas appropriate. - Rotate the session token on privilege changes, such as after MFA verification or role elevation.
Example secure login route in Fastapi with cookie rotation:
from fastapi import FastAPI, Request, Response, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
import secrets
app = Fastapi()
# In-memory store for demonstration; use Redis or similar in production
sessions = {}
@app.post("/login")
async def login(form_data: OAuth2PasswordRequestForm = Depends(), response: Response = None):
# Validate credentials (replace with your user check)
if form_data.username != "alice" or form_data.password != "secret":
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
# Invalidate any existing session associated with this user if applicable
# Generate a new random session identifier
new_session_id = secrets.token_urlsafe(32)
# Store session server-side
sessions[new_session_id] = {"user": form_data.username}
# Set a new cookie, discarding any client-supplied session cookie
response.set_cookie(
key="session_id",
value=new_session_id,
httponly=True,
secure=True,
samesite="Lax",
max_age=3600,
)
return {"message": "Logged in"}
@app.get("/protected")
async def protected(request: Request):
session_id = request.cookies.get("session_id")
if not session_id or session_id not in sessions:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Unauthorized")
return {"user": sessions[session_id]["user"]}
@app.post("/logout")
async def logout(response: Response):
# In a real app, look up session by token or use session invalidation logic
response.delete_cookie("session_id")
return {"message": "Logged out"}
For token-based APIs (e.g., JWT), ensure that tokens are not reused across authentication states and that claims such as jti are checked to prevent replay. The middleBrick Pro plan can help by enabling continuous monitoring and CI/CD integration to fail builds if insecure session handling patterns are detected in your OpenAPI specs or runtime behavior.