You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

56 lines
1.9 KiB

  1. from typing import Optional
  2. #from fastapi.openapi.models import SecurityBase as SecurityBaseModel
  3. #from fastapi.security.base import SecurityBase
  4. from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel
  5. from starlette.requests import Request
  6. from fastapi.security.utils import get_authorization_scheme_param
  7. from fastapi.security import OAuth2PasswordRequestForm, OAuth2
  8. from fastapi import Depends, FastAPI, HTTPException
  9. from starlette.status import HTTP_403_FORBIDDEN
  10. class OAuth2PasswordBearerCookie(OAuth2):
  11. def __init__(
  12. self,
  13. tokenUrl: str,
  14. scheme_name: str = None,
  15. scopes: dict = None,
  16. auto_error: bool = True,
  17. ):
  18. if not scopes:
  19. scopes = {}
  20. flows = OAuthFlowsModel(password={"tokenUrl": tokenUrl, "scopes": scopes})
  21. super().__init__(flows=flows, scheme_name=scheme_name, auto_error=auto_error)
  22. async def __call__(self, request: Request) -> Optional[str]:
  23. header_authorization: str = request.headers.get("Authorization")
  24. cookie_authorization: str = request.cookies.get("Authorization")
  25. header_scheme, header_param = get_authorization_scheme_param(
  26. header_authorization
  27. )
  28. cookie_scheme, cookie_param = get_authorization_scheme_param(
  29. cookie_authorization
  30. )
  31. if header_scheme.lower() == "bearer":
  32. authorization = True
  33. scheme = header_scheme
  34. param = header_param
  35. elif cookie_scheme.lower() == "bearer":
  36. authorization = True
  37. scheme = cookie_scheme
  38. param = cookie_param
  39. else:
  40. authorization = False
  41. if not authorization or scheme.lower() != "bearer":
  42. if self.auto_error:
  43. raise HTTPException(
  44. status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
  45. )
  46. else:
  47. return None
  48. return param