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

如何在FastAPI的add_post函数中获取HTTPBearer Token值?

解决方案

你可以通过依赖注入直接将token传入路由函数,无需引入新库,仅需调整现有代码的写法:

1. 确保你的JWTBearer类返回token字符串

如果你的JWTBearer之前只做验证不返回token,修改它的__call__方法,在验证通过后返回token(这是核心,因为依赖注入会把方法的返回值传入函数):

from fastapi import Request, HTTPException
from fastapi.security import OAuth2PasswordBearer
import jwt

# 替换成你项目里的密钥和算法
SECRET_KEY = "your-project-secret-key"
ALGORITHM = "HS256"

class JWTBearer(OAuth2PasswordBearer):
    def __init__(self, tokenUrl="login"):
        super().__init__(tokenUrl=tokenUrl)
    
    async def __call__(self, request: Request):
        # 从请求头获取token(继承OAuth2PasswordBearer的逻辑)
        token = await super().__call__(request)
        # 执行原有的token验证逻辑
        try:
            jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        except jwt.InvalidTokenError:
            raise HTTPException(status_code=401, detail="无效的token")
        # 验证通过后返回token
        return token

2. 在路由函数中注入并使用token

把原来放在dependencies里的JWTBearer移到函数参数中,通过Depends()注入,这样就能直接拿到token变量:

@app.post("/posts", tags=["posts"])
def add_post(post: PostSchema, token: str = Depends(JWTBearer())):
    # 现在可以直接使用token了
    print(f'The supplied token is {token}.')
    post.id = len(posts) + 1
    posts.append(post.dict())
    return {
        "data": "post added."
    }

补充说明

  • 你之前尝试的token:str=JWTBearer()写法错误,FastAPI必须通过Depends()来触发依赖注入流程,直接赋值类实例不会执行验证和注入逻辑。
  • 不需要保留dependencies=[Depends(JWTBearer())],因为参数注入已经会执行token验证,重复写会导致验证两次,冗余且没必要。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 08:40:18