Nexus Void Research

FastAPI, Python, API Security, JWT, Pydantic, CORS, OWASP API Security Top 10, How-to

How to Secure FastAPI Endpoints: Auth, Validation and CORS

How to secure FastAPI endpoints: router-level auth dependencies, JWT verification, object-level checks, strict Pydantic models, response models and limits.

To secure FastAPI endpoints, require authentication with a dependency (Depends(get_current_user)) applied to routers or the whole app, verify JWTs with a fixed algorithm and expiry, check authorization for the specific record inside each endpoint, validate requests with Pydantic models that forbid extra fields, return response models so you never leak internal fields, and add CORS limits, rate limiting and HTTPS. Turn off the interactive docs in production if your API is not public.

FastAPI makes it easy to ship an API quickly, and its dependency system makes security straightforward once you use it consistently. Most FastAPI security bugs are not exotic: an endpoint without the auth dependency, a query that fetches by ID without checking the owner, or a response that returns the whole database model. The OWASP API Security Top 10 lists exactly these as the top API risks. This guide shows the fixes in FastAPI code.

Step 1: Add authentication as a dependency

Define one dependency that turns a bearer token into a user, and fail closed:

from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
import jwt  # PyJWT

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

async def get_current_user(token: str = Depends(oauth2_scheme)) -> User:
    try:
        payload = jwt.decode(
            token,
            settings.jwt_secret,
            algorithms=["HS256"],          # fixed list, never taken from the token
            options={"require": ["exp", "sub"]},
        )
    except jwt.PyJWTError:
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid token",
                            headers={"WWW-Authenticate": "Bearer"})
    user = await users.get(payload["sub"])
    if user is None or not user.is_active:
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid token")
    return user
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
import jwt  # PyJWT

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

async def get_current_user(token: str = Depends(oauth2_scheme)) -> User:
    try:
        payload = jwt.decode(
            token,
            settings.jwt_secret,
            algorithms=["HS256"],          # fixed list, never taken from the token
            options={"require": ["exp", "sub"]},
        )
    except jwt.PyJWTError:
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid token",
                            headers={"WWW-Authenticate": "Bearer"})
    user = await users.get(payload["sub"])
    if user is None or not user.is_active:
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid token")
    return user
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
import jwt  # PyJWT

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

async def get_current_user(token: str = Depends(oauth2_scheme)) -> User:
    try:
        payload = jwt.decode(
            token,
            settings.jwt_secret,
            algorithms=["HS256"],          # fixed list, never taken from the token
            options={"require": ["exp", "sub"]},
        )
    except jwt.PyJWTError:
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid token",
                            headers={"WWW-Authenticate": "Bearer"})
    user = await users.get(payload["sub"])
    if user is None or not user.is_active:
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid token")
    return user

Always pass an explicit algorithms list and require exp, so tokens cannot downgrade to none or live forever. The OWASP REST Security Cheat Sheet explains why algorithm and expiry checks matter. Hash passwords with Argon2 or bcrypt through a maintained library, never with a plain hash function.

Step 2: Apply auth to whole routers, not endpoint by endpoint

Forgetting Depends(get_current_user) on one endpoint is the most common FastAPI auth bug. Attach it at the router or app level so new endpoints are protected by default:

from fastapi import APIRouter, FastAPI

private = APIRouter(prefix="/api", dependencies=[Depends(get_current_user)])
public = APIRouter(prefix="/public")

app = FastAPI()
app.include_router(public)
app.include_router(private)
from fastapi import APIRouter, FastAPI

private = APIRouter(prefix="/api", dependencies=[Depends(get_current_user)])
public = APIRouter(prefix="/public")

app = FastAPI()
app.include_router(public)
app.include_router(private)
from fastapi import APIRouter, FastAPI

private = APIRouter(prefix="/api", dependencies=[Depends(get_current_user)])
public = APIRouter(prefix="/public")

app = FastAPI()
app.include_router(public)
app.include_router(private)

Keep the list of public endpoints short and deliberate.

Step 3: Check authorization for every object

Authentication tells you who the caller is. You still need to check they may access this record:

@private.get("/invoices/{invoice_id}", response_model=InvoiceOut)
async def read_invoice(invoice_id: UUID, user: User = Depends(get_current_user),
                       db: AsyncSession = Depends(get_db)):
    invoice = await db.scalar(
        select(Invoice).where(Invoice.id == invoice_id, Invoice.owner_id == user.id)
    )
    if invoice is None:
        raise HTTPException(status.HTTP_404_NOT_FOUND)
    return invoice
@private.get("/invoices/{invoice_id}", response_model=InvoiceOut)
async def read_invoice(invoice_id: UUID, user: User = Depends(get_current_user),
                       db: AsyncSession = Depends(get_db)):
    invoice = await db.scalar(
        select(Invoice).where(Invoice.id == invoice_id, Invoice.owner_id == user.id)
    )
    if invoice is None:
        raise HTTPException(status.HTTP_404_NOT_FOUND)
    return invoice
@private.get("/invoices/{invoice_id}", response_model=InvoiceOut)
async def read_invoice(invoice_id: UUID, user: User = Depends(get_current_user),
                       db: AsyncSession = Depends(get_db)):
    invoice = await db.scalar(
        select(Invoice).where(Invoice.id == invoice_id, Invoice.owner_id == user.id)
    )
    if invoice is None:
        raise HTTPException(status.HTTP_404_NOT_FOUND)
    return invoice

Scoping the query by owner prevents IDOR, the top risk in the OWASP API list. For role checks, write small dependencies such as require_role("admin") and attach them to admin routers.

Step 4: Validate input with strict Pydantic models

FastAPI validates request bodies against your Pydantic models. Make them strict:

from pydantic import BaseModel, ConfigDict, Field

class ProfileUpdate(BaseModel):
    model_config = ConfigDict(extra="forbid")
    display_name: str = Field(min_length=1, max_length=80)
    timezone: str = Field(max_length=64)
from pydantic import BaseModel, ConfigDict, Field

class ProfileUpdate(BaseModel):
    model_config = ConfigDict(extra="forbid")
    display_name: str = Field(min_length=1, max_length=80)
    timezone: str = Field(max_length=64)
from pydantic import BaseModel, ConfigDict, Field

class ProfileUpdate(BaseModel):
    model_config = ConfigDict(extra="forbid")
    display_name: str = Field(min_length=1, max_length=80)
    timezone: str = Field(max_length=64)

extra="forbid" rejects unexpected fields, so a client cannot slip role or is_admin into an update (mass assignment). Use separate input models for create and update instead of reusing your database model.

Step 5: Use response models to avoid leaking data

Returning an ORM object directly can expose password hashes, internal flags or other users' data. Declare what goes out:

class UserOut(BaseModel):
    id: UUID
    display_name: str

@private.get("/me", response_model=UserOut)
async def me(user: User = Depends(get_current_user)):
    return user
class UserOut(BaseModel):
    id: UUID
    display_name: str

@private.get("/me", response_model=UserOut)
async def me(user: User = Depends(get_current_user)):
    return user
class UserOut(BaseModel):
    id: UUID
    display_name: str

@private.get("/me", response_model=UserOut)
async def me(user: User = Depends(get_current_user)):
    return user

FastAPI filters the response to the fields in UserOut. This addresses the OWASP API risk of exposing object properties the caller should not see.

Step 6: Lock down CORS, hosts and HTTPS

from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://app.example.com"],   # never ["*"] with credentials
    allow_credentials=True,
    allow_methods=["GET", "POST", "PATCH", "DELETE"],
    allow_headers=["Authorization", "Content-Type"],
)
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["api.example.com"])
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://app.example.com"],   # never ["*"] with credentials
    allow_credentials=True,
    allow_methods=["GET", "POST", "PATCH", "DELETE"],
    allow_headers=["Authorization", "Content-Type"],
)
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["api.example.com"])
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://app.example.com"],   # never ["*"] with credentials
    allow_credentials=True,
    allow_methods=["GET", "POST", "PATCH", "DELETE"],
    allow_headers=["Authorization", "Content-Type"],
)
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["api.example.com"])

Terminate TLS at your load balancer or proxy, and run Uvicorn with --proxy-headers and a specific --forwarded-allow-ips so client IPs and schemes are read only from your proxy.

Step 7: Rate-limit and bound requests

APIs without limits invite brute force and cost abuse:

  • Rate-limit login, signup, password reset and expensive endpoints, using a library such as SlowAPI or your API gateway.

  • Cap page sizes (limit: int = Query(20, le=100)) and request body sizes.

  • Set timeouts on outbound calls, and validate any user-supplied URL; see how to prevent SSRF.

Step 8: Hide docs and errors in production

FastAPI serves /docs, /redoc and /openapi.json by default. For an internal or partner API, turn them off in production:

app = FastAPI(
    docs_url=None if settings.env == "production" else "/docs",
    redoc_url=None,
    openapi_url=None if settings.env == "production" else "/openapi.json",
)
app = FastAPI(
    docs_url=None if settings.env == "production" else "/docs",
    redoc_url=None,
    openapi_url=None if settings.env == "production" else "/openapi.json",
)
app = FastAPI(
    docs_url=None if settings.env == "production" else "/docs",
    redoc_url=None,
    openapi_url=None if settings.env == "production" else "/openapi.json",
)

Do not run with debug tracebacks in production, and return generic error messages. Log the details server-side instead.

Step 9: Keep secrets and queries safe

  • Load configuration with pydantic-settings from environment variables or a secret manager; see how to store API keys securely.

  • Use SQLAlchemy queries or bound parameters, never f-strings in SQL; see how to prevent SQL injection.

  • Keep FastAPI, Starlette and Pydantic updated, and scan dependencies in CI.

FastAPI security checklist

Check

Done when

Auth dependency

One get_current_user that fails closed

Router-level auth

Private routers carry the dependency; public list is explicit

JWT verified

Fixed algorithms, required exp, active-user check

Object-level checks

Every query by ID is scoped to the caller

Strict input models

extra="forbid", length and type limits

Response models

Every endpoint declares what it returns

CORS and hosts

Exact origins, trusted hosts, HTTPS

Limits

Rate limits, page-size caps, timeouts

Docs and errors

Docs off for private APIs; generic errors

How does ARGUS help secure FastAPI apps?

  1. API inventory extracts the routes your code defines and marks each one Authenticated, Open (no auth found, reported as a finding) or Not determined, so an endpoint that missed the auth dependency stands out.

  2. AI business logic analysis looks for IDOR, privilege escalation and authentication bypass in Python code, and taint analysis follows request data into SQL, shell calls and outbound requests across files.

  3. Dependency scanning reads requirements.txt and Pipfile.lock, ranks FastAPI, Starlette, Pydantic and other CVEs by EPSS, CISA KEV and reachability, and marks whether your code imports the vulnerable package.

  4. Every AI finding is independently challenged before you see it, and Assign to Agent opens a verified fix pull request for you to review and merge.

Limits: AI passes run when AI scanning is enabled; reachability is import-level. See ARGUS SAST, or scan a repository free.

Frequently asked questions

How do I secure FastAPI endpoints?

Require authentication with a get_current_user dependency attached at the router or app level, verify JWTs with a fixed algorithm and required expiry, check authorization for each record, validate input with strict Pydantic models, declare response models, restrict CORS and hosts, add rate limits, and disable docs for private APIs in production.

How do I add authentication to FastAPI?

Use OAuth2PasswordBearer to read the bearer token, decode and verify it in a dependency such as get_current_user with an explicit algorithms list, load the user, and raise 401 on any failure. Attach that dependency to routers so every endpoint inside is protected by default.

How do I protect all routes in FastAPI at once?

Pass dependencies=[Depends(get_current_user)] to an APIRouter or to FastAPI() itself. Every endpoint on that router or app then requires authentication, and only routes you put on a separate public router are open. This prevents the common bug of forgetting the dependency on one endpoint.

How do I prevent mass assignment in FastAPI?

Use dedicated input models for each operation with model_config = ConfigDict(extra="forbid"), and only include fields users may set. Never bind request bodies directly to your database model, and set sensitive fields such as roles or owner IDs from server-side logic.

Should I disable /docs in FastAPI production?

For internal, partner or unpublished APIs, yes: set docs_url, redoc_url and openapi_url to None in production so you are not publishing a map of every endpoint. Public APIs can keep documentation, but the endpoints must be secure either way.

How do I configure CORS securely in FastAPI?

Add CORSMiddleware with an explicit list of your frontend origins, only the methods and headers you use, and allow_credentials=True only with exact origins. Never combine wildcard origins with credentials. CORS controls browsers only; it does not replace authentication.

How do I rate limit a FastAPI app?

Use a library such as SlowAPI to set per-route limits on login, signup, password reset and expensive endpoints, or enforce limits at an API gateway or reverse proxy. Also cap page sizes and request body sizes so one request cannot consume excessive resources.

Is FastAPI secure by default?

FastAPI provides strong building blocks, such as request validation, typed dependencies and response models, but it does not add authentication or authorization to your endpoints for you. Security depends on applying auth dependencies consistently, checking object-level access and configuring CORS, limits and production settings.

DATA SOURCES

OWASP API Security Top 10: https://owasp.org/API-Security/ ; OWASP REST Security Cheat Sheet

Liked this post? Share it: