HIGH session fixationfastapibasic auth

Session Fixation in Fastapi with Basic Auth

Session Fixation in Fastapi with Basic Auth — how this specific combination creates or exposes the vulnerability

Session fixation occurs when an application assigns a user a session identifier before authentication and does not change it after login. In Fastapi applications that use HTTP Basic Auth without additional session management, fixation risks arise because the authentication flow often relies on a session cookie to remember authenticated state. If the server sets a session cookie before validating credentials, an attacker can force a known session ID onto a victim, then trick the victim into authenticating with that session. After successful authentication, the server continues to use the same session identifier, linking the attacker’s known session to the victim’s authenticated account.

With Basic Auth, credentials are sent on every request in the Authorization header, but applications may still rely on a session cookie for CSRF protection, rate limiting, or server-side session state. If Fastapi sets a session cookie (e.g., via a middleware or dependency that assigns a session key) before verifying Basic Auth credentials, the session ID remains unchanged post-login. This creates a direct fixation path: the attacker obtains the session ID, the victim authenticates, and the server treats the authenticated request as belonging to the attacker’s session. The unauthenticated attack surface tested by middleBrick can surface this missing session rotation as a finding in the Authentication and BOLA/IDOR checks, particularly when session identifiers are predictable or not regenerated after auth.

Additionally, if the API exposes endpoints that return authentication-related metadata or session hints, attackers may infer whether session fixation is possible by observing cookie behavior across unauthenticated and authenticated requests. middleBrick’s checks for Unsafe Consumption and Data Exposure can highlight responses that inadvertently expose session identifiers or fail to set secure cookie attributes, compounding the fixation risk. Proper remediation requires ensuring session identifiers are regenerated after successful authentication and that session binding does not rely solely on pre-auth identifiers.

Basic Auth-Specific Remediation in Fastapi — concrete code fixes

To mitigate session fixation in Fastapi when using HTTP Basic Auth, rotate the session identifier immediately after successful authentication. Avoid relying on a pre-existing session ID, and ensure that any server-side session store creates a new key upon login. Below is a concrete, secure pattern using Fastapi dependencies and HTTP Basic Auth that regenerates the session after credential validation.

from fastapi import Fastapi, Depends, HTTPException, Response, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
import secrets
from typing import Dict

app = Fastapi()
security = HTTPBasic()

# In-memory store for demonstration; replace with a secure session store in production
session_store: Dict[str, str] = {}

def verify_credentials(credentials: HTTPBasicCredentials):
    # Replace with secure credential verification (e.g., hashed comparison)
    if credentials.username == "alice" and credentials.password == "secret":
        return True
    return False

def get_session_id(response: Response) -> str:
    # Generate a new, unpredictable session identifier
    return secrets.token_urlsafe(32)

@app.post("/login")
async def login(response: Response, credentials: HTTPBasicCredentials = Depends(security)):
    if not verify_credentials(credentials):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password"
        )
    # Rotate session after successful authentication
    new_session_id = get_session_id(response)
    # Bind the new session to the authenticated user (e.g., by username)
    session_store[new_session_id] = credentials.username
    # Set secure cookie attributes; adjust as needed for your deployment
    response.set_cookie(
        key="session_id",
        value=new_session_id,
        httponly=True,
        secure=True,
        samesite="lax",
    )
    return {"message": "Authenticated"}

@app.get("/protected")
async def protected(session_id: str = None):
    session_id = session_id or (request.cookies.get("session_id") if request else None)
    if not session_id or session_store.get(session_id) is None:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Unauthorized")
    return {"user": session_store[session_id]}

This example demonstrates generating a fresh session ID after verifying Basic Auth credentials and binding it to the authenticated identity. The cookie is set with secure attributes to reduce exposure over insecure channels. middleBrick’s checks for Authentication and Property Authorization can help verify that session rotation is enforced and that endpoints properly validate session binding, reducing the risk of fixation.

For teams using the middleBrick CLI, running middlebrick scan <url> can surface missing session rotation and insecure cookie practices as part of the unauthenticated scan. If you require continuous oversight, the Pro plan supports continuous monitoring for up to 100 APIs and can integrate via the GitHub Action to fail builds if risk scores fall below your defined thresholds.

Frequently Asked Questions

Can session fixation occur with token-based authentication instead of sessions?
Yes. If a token is issued before authentication and reused after login without being rotated or re-issued, an attacker can fixate the token. Always re-issue tokens after successful authentication and avoid reusing pre-auth tokens.
How does middleBrick detect session fixation risks in Basic Auth APIs?
middleBrick runs unauthenticated checks that inspect authentication flows, session handling, and cookie attributes. Findings related to missing session rotation, predictable identifiers, or weak cookie settings appear in the Authentication and Unsafe Consumption checks, with remediation guidance included in the report.