FastAPI 安全配置指南

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

1. 禁用文档接口

你可以通过设置 docs_url 和 redoc_url 为 None 来禁用 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 应用。

相关推荐
比特屿35 分钟前
Spring AI 2.1实战(七):RAG上篇,把私有文档喂给模型
java·后端
极客先躯36 分钟前
智能体开发高级面试每日一题|2026-05-26|Agent 和 Workflow 的区别是什么?什么场景该用 Workflow,什么场景该用 Agent?
ai·面试·职场和发展·架构·每日一题·高级面试·智能体开发
stormsha1 小时前
MySQL 起不来只报 `Failed to set datadir`:真凶是 my.ini 里的四个字符
数据库·后端·mysql
打工仔折腾 AI1 小时前
智能体开发实战:Agent架构拆解与ReAct执行循环工程落地
前端·后端·python·react.js·架构·langchain·ai agent 实战
北城笑笑1 小时前
Vue 115 ,上篇:给智能体装上计费表,行知订阅次数额度与每日额度双规则设计( 需求分析与方案设计,Vue3 + RuoYi 3.9.2 + 主子账号 )
java·前端·javascript·数据库·vue.js·后端·vue
海边捡石子1 小时前
用 Nuitka 保护 Python 核心业务源码
linux·后端·python
GuWenyue1 小时前
订单号末尾变成了 0,对账还少了 1 分钱:一个 53 位尾数惹的祸
javascript·数据库·后端
小南舟1 小时前
审批该用飞书审批还是自建流程引擎?三条判据,外加一个删不掉的定义
后端·api
stormsha1 小时前
`Connection is not available, request timed out after 30000ms`:不是数据库慢,是池子空了
java·后端·mysql
不要试图纠正别人1 小时前
结构化并发不撒谎,代价是把线程泄漏换成请求挂死
java·后端