FastAPI 安全配置指南

FastAPI 是一个现代化的 Python Web 框架,提供了快速开发 API 的能力。为了确保应用的安全性,我们需要配置一些关键的安全设置。以下是关于如何在 FastAPI 中避免文档暴露以及其他安全配置的详细指南。

1. 禁用文档接口

你可以通过设置 docs_urlredoc_urlNone 来禁用 Swagger UI 和 ReDoc 文档接口。

python 复制代码
from fastapi import FastAPI

app = FastAPI(docs_url=None, redoc_url=None)

2. 隐藏部分接口

使用 include_in_schema=False 参数可以隐藏部分接口。

python 复制代码
from fastapi import FastAPI

app = FastAPI()

@app.post("/login", include_in_schema=False)
def login(params: LoginInfo):
    # 登录逻辑
    pass

3. 使用环境变量控制文档显示

根据环境变量决定是否显示文档。

python 复制代码
import os
from fastapi import FastAPI

env = os.getenv('env')

if env != 'develop':
    app = FastAPI(docs_url=None, redoc_url=None)
else:
    app = FastAPI()

4. HTTPS 配置

使用 HTTPS 加密数据传输,保护敏感信息。

  • 重要性: HTTPS 防止数据被拦截或篡改。
  • 实现方式: 使用 SSL/TLS 证书,通过 Uvicorn 启用 HTTPS。
bash 复制代码
uvicorn main:app --host 0.0.0.0 --port 8000 --cert /path/to/cert.pem --key /path/to/key.pem

5. 安全头部配置

添加安全头部防止 XSS、Clickjacking 等攻击。

  • 重要性: 防止常见的 Web 攻击。
  • 实现方式: 使用 FastAPI 中间件添加安全头部。
python 复制代码
from fastapi import FastAPI, Response
from fastapi.responses import JSONResponse

app = FastAPI()

@app.middleware("http")
async def add_security_headers(request, call_next):
    response = await call_next(request)
    response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
    response.headers["X-Frame-Options"] = "SAMEORIGIN"
    return response

6. 输入验证和数据清理

使用 Pydantic 模型防止 SQL 注入、XSS 等攻击。

  • 重要性: 自动验证和清理输入数据。
  • 实现方式: 定义 Pydantic 模型。
python 复制代码
from pydantic import BaseModel

class User(BaseModel):
    username: str
    password: str

@app.post("/register")
def register(user: User):
    # 注册逻辑
    pass

7. CORS 配置

限制跨域请求,防止不必要的交互。

  • 重要性: 限制跨域访问。
  • 实现方式 : 使用 CORSMiddleware 配置允许的来源、方法和头部。
python 复制代码
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

origins = [
    "http://localhost:3000",
    "http://localhost:8000",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

8. CSRF 保护

使用 CSRF 令牌防止跨站请求伪造攻击。

  • 重要性: 防止 CSRF 攻击。
  • 实现方式 : 使用 CSRFMiddleware 添加 CSRF 令牌保护。
python 复制代码
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

app = FastAPI()

@app.post("/submit")
def submit(request: Request):
    # 提交逻辑
    pass

注意: FastAPI 本身不提供内置的 CSRF 保护,需要使用第三方库或自行实现。

9. 速率限制

使用 fastapi-limiter 库防止滥用和 DDoS 攻击。

  • 重要性: 防止滥用。
  • 实现方式: 设置速率限制。
python 复制代码
from fastapi import FastAPI
from fastapi_limiter import FastAPILimiter
from fastapi_limiter.limit import RateLimit

app = FastAPI()

limiter = FastAPILimiter()

@app.get("/api/data")
@RateLimit(limit=10, period=60)  # 每分钟最多请求 10 次
def get_data():
    # 数据获取逻辑
    pass

limiter.init_app(app)

10. 依赖更新和管理

定期更新依赖库,防止已知漏洞利用。

  • 重要性: 保持依赖库更新。
  • 实现方式 : 使用 pip 更新依赖库。
bash 复制代码
pip install --upgrade -r requirements.txt

11. 错误处理和日志管理

实现安全的错误处理机制,避免日志中包含敏感信息。

  • 重要性: 避免泄露敏感信息。
  • 实现方式: 实现自定义错误处理。
python 复制代码
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

app = FastAPI()

@app.exception_handler(Exception)
async def handle_exception(request: Request, exc: Exception):
    return JSONResponse(status_code=500, content={"message": "Internal Server Error"})

12. RBAC(基于角色的访问控制)

限制用户访问,确保只有授权用户可以访问特定资源。

  • 重要性: 限制用户访问。
  • 实现方式: 使用依赖注入和安全作用域定义用户角色和权限。
python 复制代码
from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/admin")
def read_admin(token: str = Depends(oauth2_scheme)):
    # 管理员接口逻辑
    pass

通过这些配置和措施,你可以构建一个更安全的 FastAPI 应用。

相关推荐
追逐时光者几秒前
C#/.NET/.NET Core技术前沿周刊 | 第 33 期(2025年4.1-4.6)
后端·.net
灼华十一13 分钟前
Golang系列 - 内存对齐
开发语言·后端·golang
兰亭序咖啡28 分钟前
学透Spring Boot — 009. Spring Boot的四种 Http 客户端
java·spring boot·后端
独行soc38 分钟前
2025年渗透测试面试题总结- 某四字大厂面试复盘扩展 一面(题目+回答)
java·数据库·python·安全·面试·职场和发展·汽车
Asthenia041239 分钟前
深入解析Pandas索引机制:离散选择与聚合选择的差异及常见误区
后端
zew10409945881 小时前
基于spring boot的外卖系统的设计与实现【如何写论文思路与真正写出论文】
spring boot·后端·毕业设计·论文·外卖系统·辅导·查重
东方雴翾1 小时前
Scala语言的分治算法
开发语言·后端·golang
李慕瑶1 小时前
Scala语言的移动UI设计
开发语言·后端·golang
Sissar1 小时前
变更日志0..1.0
github