security-fastapi
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinese<overview>
Security audit patterns for FastAPI applications covering authentication dependencies, CORS configuration, and middleware security.
</overview>
<vulnerabilities><overview>
FastAPI应用的安全审计模式,涵盖认证依赖项、CORS配置和中间件安全。
</overview>
<vulnerabilities>Core Risks to Check
需检查的核心风险
Missing Auth on Routes
路由缺失认证
FastAPI expects authentication/authorization via dependencies on routes or routers. If no / usage exists, review every route for unintended public access.
Depends()Security()python
from fastapi import Depends, Security
@app.get("/private")
async def private_route(user=Depends(get_current_user)):
return {"ok": True}
@app.get("/scoped")
async def scoped_route(user=Security(get_current_user, scopes=["items"])):
return {"ok": True}FastAPI期望通过路由或路由器上的依赖项实现认证/授权。如果未使用/,需检查每个路由是否存在意外的公共访问情况。
Depends()Security()python
from fastapi import Depends, Security
@app.get("/private")
async def private_route(user=Depends(get_current_user)):
return {"ok": True}
@app.get("/scoped")
async def scoped_route(user=Security(get_current_user, scopes=["items"])):
return {"ok": True}API Key Schemes
API密钥方案
If using API keys, SHOULD prefer header-based schemes () and validate the key server-side.
APIKeyHeaderpython
from fastapi import Depends, FastAPI
from fastapi.security import APIKeyHeader
api_key = APIKeyHeader(name="x-api-key")
@app.get("/items")
async def read_items(key: str = Depends(api_key)):
return {"key": key}如果使用API密钥,应优先采用基于头部的方案()并在服务器端验证密钥。
APIKeyHeaderpython
from fastapi import Depends, FastAPI
from fastapi.security import APIKeyHeader
api_key = APIKeyHeader(name="x-api-key")
@app.get("/items")
async def read_items(key: str = Depends(api_key)):
return {"key": key}CORS: Avoid Wildcards with Credentials
CORS:避免在启用凭证时使用通配符
Using excludes credentialed requests (cookies/Authorization). For authenticated browser clients, MUST explicitly list allowed origins.
allow_origins=["*"]python
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["https://app.example.com"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)使用会排除带凭证的请求(Cookie/Authorization)。对于已认证的浏览器客户端,必须显式列出允许的源地址。
allow_origins=["*"]python
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["https://app.example.com"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)Host Header and HTTPS Enforcement
主机头与HTTPS强制
SHOULD use Starlette middleware to prevent host-header attacks and enforce HTTPS in production.
python
from starlette.middleware.trustedhost import TrustedHostMiddleware
from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["example.com", "*.example.com"])
app.add_middleware(HTTPSRedirectMiddleware)应使用Starlette中间件防止主机头攻击,并在生产环境中强制使用HTTPS。
python
from starlette.middleware.trustedhost import TrustedHostMiddleware
from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["example.com", "*.example.com"])
app.add_middleware(HTTPSRedirectMiddleware)Quick Audit Commands
快速审计命令
bash
undefinedbash
undefinedDetect FastAPI usage
Detect FastAPI usage
rg -n "fastapi" pyproject.toml requirements*.txt
rg -n "fastapi" pyproject.toml requirements*.txt
Find routes
Find routes
rg -n "@app.(get|post|put|patch|delete)" . -g "*.py"
rg -n "@app.(get|post|put|patch|delete)" . -g "*.py"
Check for auth dependencies
Check for auth dependencies
rg -n "Depends(|Security(" . -g "*.py"
rg -n "Depends(|Security(" . -g "*.py"
CORS config and wildcards
CORS config and wildcards
rg -n "CORSMiddleware|allow_origins|allow_credentials" . -g "*.py"
rg -n "CORSMiddleware|allow_origins|allow_credentials" . -g "*.py"
TrustedHost/HTTPS middleware
TrustedHost/HTTPS middleware
rg -n "TrustedHostMiddleware|HTTPSRedirectMiddleware" . -g "*.py"
</commands>
<checklist>rg -n "TrustedHostMiddleware|HTTPSRedirectMiddleware" . -g "*.py"
</commands>
<checklist>Hardening Checklist
加固清单
- All sensitive routes require or
Depends()auth dependenciesSecurity() - API key schemes use headers (), not query params
APIKeyHeader - is explicit when
allow_originsallow_credentials=True - configured for production domains
TrustedHostMiddleware - enabled in production (or enforced by proxy)
HTTPSRedirectMiddleware
- 所有敏感路由都要求使用或
Depends()认证依赖项Security() - API密钥方案使用头部()而非查询参数
APIKeyHeader - 当时,
allow_credentials=True设置为显式值allow_origins - 为生产环境域名配置
TrustedHostMiddleware - 生产环境中启用(或由代理强制实施)
HTTPSRedirectMiddleware
Scripts
脚本
- - First-pass FastAPI security scan
scripts/scan.sh
- - FastAPI安全初步扫描脚本
scripts/scan.sh