You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在FastAPI中间件中使用fastapi_another_jwt_auth而非依赖注入?

可以在中间件中使用fastapi_another_jwt_auth吗?

答案是肯定的——你可以在中间件中使用fastapi_another_jwt_auth,但需要针对中间件的运行逻辑做一些适配,毕竟这个库原本是围绕FastAPI的依赖注入设计的。下面是具体的实现思路和注意事项:

核心实现步骤

1. 编写认证中间件

先定义中间件类,在其中完成白名单判断、Token校验逻辑:

from fastapi import Request
from fastapi.responses import JSONResponse
from fastapi_another_jwt_auth import AuthJWT
from fastapi_another_jwt_auth.exceptions import AuthJWTException

# 定义无需认证的白名单端点
WHITELIST_PATHS = ["/login", "/docs", "/redoc"]

class AuthMiddleware:
    def __init__(self, app):
        self.app = app

    async def __call__(self, request: Request, call_next):
        # 白名单端点直接放行
        if request.url.path in WHITELIST_PATHS:
            return await call_next(request)
        
        # 提取请求头中的Token
        auth_header = request.headers.get("Authorization")
        if not auth_header or not auth_header.startswith("Bearer "):
            return JSONResponse(
                status_code=401,
                content={"detail": "缺少有效Authorization头"}
            )
        token = auth_header.split(" ")[1]
        
        try:
            # 初始化AuthJWT实例并校验Token
            auth_jwt = AuthJWT(request)
            await auth_jwt.verify_token(token)
            # 将用户标识存入request.state,供后续端点使用
            request.state.user_id = await auth_jwt.get_jwt_subject()
        except AuthJWTException as e:
            return JSONResponse(
                status_code=401,
                content={"detail": str(e)}
            )
        
        # 校验通过,继续处理请求
        return await call_next(request)

2. 注册中间件(支持测试时禁用)

在创建FastAPI应用时,通过环境变量控制是否加载认证中间件,方便测试:

import os
from fastapi import FastAPI

app = FastAPI()

# 非测试环境才注册认证中间件
if not os.getenv("TESTING"):
    app.add_middleware(AuthMiddleware)

3. 测试时的配置

在测试代码中设置环境变量,禁用中间件:

import os
os.environ["TESTING"] = "True"

from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

def test_protected_endpoint():
    # 无需携带Token即可访问,简化测试流程
    response = client.get("/protected")
    assert response.status_code == 200

关键注意事项

  • 用户信息传递:中间件无法像依赖注入那样直接将用户信息作为参数传入端点函数,需要通过request.state存储,端点内通过request.state.user_id读取。
  • 场景适配:中间件适合全局统一认证规则的场景;如果部分端点需要特殊权限校验,依赖注入的方式会更灵活。
  • 异常一致性:确保中间件的异常处理逻辑(如Token过期、无效)和依赖注入时的行为一致,避免出现认证结果不一致的情况。

内容的提问来源于stack exchange,提问作者Beast

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 19:10:31