如何用三层防护体系打造坚不可摧的 API 安全堡垒?

扫描二维码

关注或者微信搜一搜:编程智域 前端至全栈交流与成长

发现1000+提升效率与开发的AI工具和实用程序https://tools.cmdragon.cn/

FastAPI 安全与认证综合实战

通过三层防护体系实现API安全:

  1. 传输层:HTTPS + CORS配置
  2. 认证层:OAuth2 + JWT令牌
  3. 权限层:RBAC模型 + 操作日志审计

一、JWT 认证联调方案

sequenceDiagram participant 用户 participant FastAPI participant 数据库 用户->>FastAPI: 提交用户名密码 FastAPI->>数据库: 验证凭证 数据库-->>FastAPI: 返回用户数据 FastAPI->>FastAPI: 生成JWT令牌 FastAPI-->>用户: 返回access_token 用户->>FastAPI: 携带Bearer token FastAPI->>FastAPI: 解码验证token FastAPI->>数据库: 获取用户权限 FastAPI-->>用户: 返回受保护资源

实现步骤

python 复制代码
# 安装依赖:pip install python-jose[cryptography]==3.3.0 passlib==1.7.4
from jose import JWTError, jwt
from datetime import datetime, timedelta

SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30


def create_access_token(data: dict):
    to_encode = data.copy()
    expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    to_encode.update({"exp": expire})
    return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)


async def get_current_user(token: str = Depends(oauth2_scheme)):
    credentials_exception = HTTPException(
        status_code=401,
        detail="无法验证凭证",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
    except JWTError:
        raise credentials_exception
    return username

二、OAuth2 集成实现

graph TD A[用户] -->|登录| B(认证服务器) B -->|授权码| A A -->|提交授权码| C[客户端] C -->|换取令牌| B B -->|访问令牌| C C -->|访问资源| D[资源服务器]

第三方登录配置

python 复制代码
# 配置示例:pip install authlib==1.0.1
from fastapi.security import OAuth2AuthorizationCodeBearer

oauth2_scheme = OAuth2AuthorizationCodeBearer(
    authorizationUrl='https://provider.com/auth',
    tokenUrl='https://provider.com/token',
    scopes={"read": "读取权限", "write": "写入权限"}
)


@app.get("/login/google")
async def login_google():
    return RedirectResponse(
        url=(
            "https://accounts.google.com/o/oauth2/auth"
            "?response_type=code"
            "&client_id=your-client-id"
            "&redirect_uri=http://localhost:8000/callback"
            "&scope=openid%20profile%20email"
        )
    )

三、渗透测试实战案例

flowchart TB A[信息收集] --> B[漏洞扫描] B --> C{存在漏洞?} C -->|是| D[渗透攻击] C -->|否| E[生成报告] D --> F[权限提升] F --> G[数据窃取] G --> E

  1. XSS测试:在输入字段注入 <script>alert(1)</script>
  2. SQL注入测试:' OR 1=1 --
  3. 越权访问测试:修改用户ID参数
  4. SQL 注入防护方案
python 复制代码
# 使用SQLAlchemy防止注入(pip install sqlalchemy==1.4.46)
from sqlalchemy import text


@app.get("/items/")
async def read_items(name: str):
    # 错误写法:f"SELECT * FROM items WHERE name = '{name}'"
    query = text("SELECT * FROM items WHERE name = :name")
    result = await database.execute(query, {"name": name})
    return result.fetchall()

课后 Quiz

  1. 问题:JWT 令牌应该存储在客户端的哪个位置最安全?

    • A) localStorage
    • B) sessionStorage
    • C) HTTPOnly Cookie
    • D) URL 参数

    答案:C。HTTPOnly Cookie 可以防止XSS攻击窃取令牌,配合Secure和SameSite属性使用更安全。

  2. 问题:当收到401 Unauthorized响应时,首先应该检查:

    • A) 路由配置
    • B) 令牌有效期
    • C) 数据库连接
    • D) 请求头格式

    答案:B。令牌过期是最常见的401错误原因,需检查令牌生成时间和有效期设置。

常见报错处理

错误现象:422 Validation Error

json 复制代码
{
  "detail": [
    {
      "loc": [
        "body",
        "password"
      ],
      "msg": "field required",
      "type": "value_error.missing"
    }
  ]
}

解决方案

  1. 检查请求体是否包含所有必填字段
  2. 验证请求头 Content-Type 是否为 application/json
  3. 使用 Pydantic 模型进行数据验证:
python 复制代码
class UserCreate(BaseModel):
    username: str = Field(min_length=3)
    password: str = Field(min_length=8, regex="^(?=.*[A-Za-z])(?=.*\d).{8,}$")

余下文章内容请点击跳转至 个人博客页面 或者 扫码关注或者微信搜一搜:编程智域 前端至全栈交流与成长

,阅读完整的文章:如何在FastAPI中玩转JWT认证与OAuth2集成,同时确保安全无虞?

往期文章归档:

免费好用的热门在线工具