python FastAPI -支持基本身份验证或JWT身份验证访问端点

vawmfj5a  于 2024-10-23  发布在  Python
关注(0)|答案(1)|浏览(164)

链接:fastapi-supporting-multiple-authentication-dependencies
我认为这是最接近我所需要的,但不知何故,我不能让任何一个依赖工作,因为fastapi在赠款对endpoint的访问之前强制执行两个依赖。
客户依赖性的筛选:

  1. def basic_logged_user(credentials: Annotated[HTTPBasicCredentials, Depends(security)]):
  2. current_username_bytes = credentials.username.encode("utf8")
  3. correct_username_bytes = settings.SESSION_LOGIN_USER.encode("utf8")
  4. is_correct_username = secrets.compare_digest(
  5. current_username_bytes, correct_username_bytes
  6. )
  7. current_password_bytes = credentials.password.encode("utf8")
  8. correct_password_bytes = settings.SESSION_LOGIN_PASS.encode("utf8")
  9. is_correct_password = secrets.compare_digest(
  10. current_password_bytes, correct_password_bytes
  11. )
  12. if not (is_correct_username and is_correct_password):
  13. raise HTTPException(
  14. status_code=status.HTTP_401_UNAUTHORIZED,
  15. detail="Invalid Credentials",
  16. headers={"WWW-Authenticate": "Basic"},
  17. )
  18. return credentials.username
  19. def jwt_logged_user(token: str = Depends(utils.OAuth2_scheme),
  20. db: Session = Depends(db_session)):
  21. credential_exception = HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
  22. detail="Incorrect username or password",
  23. headers={"WWW-Authenticate": "Bearer"})
  24. token = utils.verify_token(token, credential_exception)
  25. user = db.query(User).filter(User.username == token.username).first()
  26. return user
  27. # custom auth
  28. def auth_user(jwt_auth: HTTPBearer = Depends(jwt_logged_user),
  29. basic_auth: HTTPBasic = Depends(basic_logged_user)):
  30. if not (jwt_auth or basic_auth):
  31. raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
  32. detail='Invalid Credentials')
  33. #endpoint
  34. @router.get("/")
  35. async def get_users(db: Session = Depends(db_session), logged_user: str = Depends(auth_user)):
  36. query_users = db.query(User).all()
  37. return query_users

字符串
我希望当我为JWT认证或基本认证提供正确的凭据时,它会授予我访问端点的权限,但它仍然迫使我为两者都提供凭据。我如何才能实现提供两个认证中的任何一个而不是两者的效果。

0s0u357o

0s0u357o1#

这个想法是使所有这些安全依赖项在依赖项解析阶段不会引发用户身份验证错误的异常。
对于HTTPBasic通过auto_error=False

  1. security = HTTPBasic(auto_error=False)

字符串
然后在basic_logged_user中,你应该检查

  1. def basic_logged_user(credentials: Annotated[Optional[HTTPBasicCredentials], Depends(security)]):
  2. if credentials is None:
  3. return None
  4. ...
  5. # Do not raise exception, but return None instead


您需要找到如何对第二个身份验证方案(utils.OAuth2_scheme)执行相同操作的方法-不是引发HTTP_401_UNAUTHORIZED,而是返回None
那么你的auth_user就会像你期望的那样工作,只有当两个方案都返回None时,它才会引发HTTP_401_UNAUTHORIZED

展开查看全部

相关问题