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:
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:
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:
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:
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:
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
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:
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-settingsfrom 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 |
Router-level auth | Private routers carry the dependency; public list is explicit |
JWT verified | Fixed |
Object-level checks | Every query by ID is scoped to the caller |
Strict input models |
|
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?
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.
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.
Dependency scanning reads
requirements.txtandPipfile.lock, ranks FastAPI, Starlette, Pydantic and other CVEs by EPSS, CISA KEV and reachability, and marks whether your code imports the vulnerable package.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