我需要创建一个带有路由的 API,该 API 能够识别当前用户是否是请求中指定的用户(也没有身份验证应该是有效的)
对于我遵循的其他路径 https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/ 并且一切都与带有 JWT 令牌的 Bearer 一起使用
user: User = Depends(get_current_active_user)
修改我尝试使用的文档提供的方法
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth")
async def get_user_or_none(db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)):
"""
Return the current active user if is present (using the token Bearer) or None
"""
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
return None
except JWTError:
return None
# check user in db
user = crud.get_user(db, username)
if user is None:
return None
return user
@router.get("/api/{user_id}/structure")
async def get_user_structure(
user_id: int,
user = Depends(get_user_or_none),
db: Session = Depends(get_db)
):
# do_something() if user.id == user_id else do_something_else()
但我收到一个错误
401 Error: Unauthorized {
"detail": "Not authenticated"
}
答案 0 :(得分:0)
您需要对这些带有 OAuth2PasswordBearer
的可选身份验证端点使用不同的 auto_error=False
,例如
optional_oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth", auto_error=False)
async def get_user_or_none(db: Session = Depends(get_db), token: str = Depends(optional_oauth2_scheme)):
...
现在,当未提供 None
标头时,令牌将为 Authorization
,从而导致您想要的行为。