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

FastAPI中JWT Token存入Cookie后get_current_user函数失效问题

解决JWT存入Cookie后get_current_user无法获取用户数据的问题

核心原因

你当前使用的oauth2_scheme(默认是OAuth2PasswordBearer实例)只会从HTTP请求的Authorization头中解析Bearer <token>格式的Token,而你将Token存入了名为Bearer的Cookie中,两者的获取路径不匹配,导致get_current_user无法拿到有效Token,进而无法完成用户验证。

解决方案

方案1:自定义依赖从Cookie中获取Token

直接替换默认的oauth2_scheme,编写一个从Cookie读取Token的依赖函数:

from fastapi import Cookie, HTTPException, status

# 自定义从Cookie获取Token的依赖
async def get_token_from_cookie(Bearer: str | None = Cookie(None)):
    if not Bearer:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Could not validate credentials",
        )
    return Bearer

修改get_current_user的依赖参数,使用上面的自定义函数:

async def get_current_user(token: str = Depends(get_token_from_cookie), db: Session = Depends(get_db)):
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        #headers={"WWW-Authenticate": "Bearer"},  
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        mobile_number: str = payload.get("sub")
        if mobile_number is None:
            raise credentials_exception
        token_data = schemas.TokenData(mobile_number=mobile_number)
    except JWTError:
        raise credentials_exception
    user = db.query(models.User).filter(models.User.mobile_number==mobile_number).first()
    if user is None:
        raise credentials_exception
    return user

方案2:同时支持Authorization头和Cookie获取Token

如果需要兼容两种Token传递方式(请求头和Cookie),可以编写一个同时检查两者的依赖:

async def get_token_from_header_or_cookie(
    token: str | None = Depends(oauth2_scheme),
    Bearer: str | None = Cookie(None)
):
    # 优先取Authorization头的Token,没有则取Cookie中的值
    if not token:
        token = Bearer
    if not token:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Could not validate credentials",
        )
    return token

将get_current_user的token参数依赖替换为这个函数即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 00:01:16