FastAPI中JWT Token存入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
相关产品推荐
相关产品推荐

