v0.14 is out: a mobile auth pack for Swift/iOS and Android, catching insecure token storage, cleartext traffic, and OAuth in embedded WebViews. Read more →
HIGH AI PREVALENCE: HIGH auth.py.fastapi.session-hardcoded-secret

Starlette's SessionMiddleware is configured with a hard-coded secret_key string literal.

Why AI tools produce this: AI coding tools generate this anti-pattern by default, it appears in a large share of AI-written auth code.

Why this matters

That key signs every session cookie: anyone who reads the source or a leaked repo can forge a session and impersonate any user, a complete authentication bypass (CWE-798). This is a common AI-generated shortcut, where a literal secret is inlined so the sample "just works" and is never externalized.

Load the key from the environment or a secret manager instead, e.g. app.add_middleware(SessionMiddleware, secret_key=os.environ["SESSION_SECRET"]), and generate it with a CSPRNG such as secrets.token_hex(32). Rotate the leaked secret out of source control.

VULNERABLE
vulnerable.py
from fastapi import FastAPI
from starlette.middleware.sessions import SessionMiddleware

app = FastAPI()

# ruleid: auth.py.fastapi.session-hardcoded-secret
app.add_middleware(SessionMiddleware, secret_key="super-secret-value-123")

# ruleid: auth.py.fastapi.session-hardcoded-secret
app.add_middleware(
    SessionMiddleware,
    secret_key="another-hardcoded-key",
    session_cookie="sid",
    max_age=3600,
)

# Direct instantiation form.
# ruleid: auth.py.fastapi.session-hardcoded-secret
mw = SessionMiddleware(app, secret_key="inline-literal-secret")
SAFE
safe.py
import os
import secrets

from fastapi import FastAPI
from starlette.middleware.sessions import SessionMiddleware

app = FastAPI()

# Loaded from the environment.
# ok: auth.py.fastapi.session-hardcoded-secret
app.add_middleware(SessionMiddleware, secret_key=os.environ["SESSION_SECRET"])

# Settings reference.
# ok: auth.py.fastapi.session-hardcoded-secret
app.add_middleware(SessionMiddleware, secret_key=settings.session_secret)

# Generated with a CSPRNG.
# ok: auth.py.fastapi.session-hardcoded-secret
app.add_middleware(SessionMiddleware, secret_key=secrets.token_hex(32))

# Obvious placeholder / env template — not a real secret.
# ok: auth.py.fastapi.session-hardcoded-secret
app.add_middleware(SessionMiddleware, secret_key="${SESSION_SECRET}")

# ok: auth.py.fastapi.session-hardcoded-secret
app.add_middleware(SessionMiddleware, secret_key="changeme")

Suppressing this rule

If a finding is a genuine false positive, scope the suppression to the exact line and leave a reason, never disable the rule project-wide. Disable directives are line-scoped by design.

# oauthlint-disable-next-line auth.py.fastapi.session-hardcoded-secret -- <reason>

References

https://www.starlette.io/middleware/#sessionmiddleware ↗https://cwe.mitre.org/data/definitions/798.html ↗