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.
 
 
 
 

221 lines
8.0 KiB

  1. from typing import Any, Dict, List, Optional, Union
  2. from fastapi.exceptions import HTTPException
  3. from fastapi.openapi.models import OAuth2 as OAuth2Model
  4. from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel
  5. from fastapi.param_functions import Form
  6. from fastapi.security.base import SecurityBase
  7. from fastapi.security.utils import get_authorization_scheme_param
  8. from starlette.requests import Request
  9. from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN
  10. class OAuth2PasswordRequestForm:
  11. """
  12. This is a dependency class, use it like:
  13. @app.post("/login")
  14. def login(form_data: OAuth2PasswordRequestForm = Depends()):
  15. data = form_data.parse()
  16. print(data.username)
  17. print(data.password)
  18. for scope in data.scopes:
  19. print(scope)
  20. if data.client_id:
  21. print(data.client_id)
  22. if data.client_secret:
  23. print(data.client_secret)
  24. return data
  25. It creates the following Form request parameters in your endpoint:
  26. grant_type: the OAuth2 spec says it is required and MUST be the fixed string "password".
  27. Nevertheless, this dependency class is permissive and allows not passing it. If you want to enforce it,
  28. use instead the OAuth2PasswordRequestFormStrict dependency.
  29. username: username string. The OAuth2 spec requires the exact field name "username".
  30. password: password string. The OAuth2 spec requires the exact field name "password".
  31. scope: Optional string. Several scopes (each one a string) separated by spaces. E.g.
  32. "items:read items:write users:read profile openid"
  33. client_id: optional string. OAuth2 recommends sending the client_id and client_secret (if any)
  34. using HTTP Basic auth, as: client_id:client_secret
  35. client_secret: optional string. OAuth2 recommends sending the client_id and client_secret (if any)
  36. using HTTP Basic auth, as: client_id:client_secret
  37. """
  38. def __init__(
  39. self,
  40. grant_type: str = Form(None, regex="password"),
  41. username: str = Form(...),
  42. password: str = Form(...),
  43. scope: str = Form(""),
  44. client_id: Optional[str] = Form(None),
  45. client_secret: Optional[str] = Form(None),
  46. ):
  47. self.grant_type = grant_type
  48. self.username = username
  49. self.password = password
  50. self.scopes = scope.split()
  51. self.client_id = client_id
  52. self.client_secret = client_secret
  53. class OAuth2PasswordRequestFormStrict(OAuth2PasswordRequestForm):
  54. """
  55. This is a dependency class, use it like:
  56. @app.post("/login")
  57. def login(form_data: OAuth2PasswordRequestFormStrict = Depends()):
  58. data = form_data.parse()
  59. print(data.username)
  60. print(data.password)
  61. for scope in data.scopes:
  62. print(scope)
  63. if data.client_id:
  64. print(data.client_id)
  65. if data.client_secret:
  66. print(data.client_secret)
  67. return data
  68. It creates the following Form request parameters in your endpoint:
  69. grant_type: the OAuth2 spec says it is required and MUST be the fixed string "password".
  70. This dependency is strict about it. If you want to be permissive, use instead the
  71. OAuth2PasswordRequestForm dependency class.
  72. username: username string. The OAuth2 spec requires the exact field name "username".
  73. password: password string. The OAuth2 spec requires the exact field name "password".
  74. scope: Optional string. Several scopes (each one a string) separated by spaces. E.g.
  75. "items:read items:write users:read profile openid"
  76. client_id: optional string. OAuth2 recommends sending the client_id and client_secret (if any)
  77. using HTTP Basic auth, as: client_id:client_secret
  78. client_secret: optional string. OAuth2 recommends sending the client_id and client_secret (if any)
  79. using HTTP Basic auth, as: client_id:client_secret
  80. """
  81. def __init__(
  82. self,
  83. grant_type: str = Form(..., regex="password"),
  84. username: str = Form(...),
  85. password: str = Form(...),
  86. scope: str = Form(""),
  87. client_id: Optional[str] = Form(None),
  88. client_secret: Optional[str] = Form(None),
  89. ):
  90. super().__init__(
  91. grant_type=grant_type,
  92. username=username,
  93. password=password,
  94. scope=scope,
  95. client_id=client_id,
  96. client_secret=client_secret,
  97. )
  98. class OAuth2(SecurityBase):
  99. def __init__(
  100. self,
  101. *,
  102. flows: Union[OAuthFlowsModel, Dict[str, Dict[str, Any]]] = OAuthFlowsModel(),
  103. scheme_name: Optional[str] = None,
  104. description: Optional[str] = None,
  105. auto_error: Optional[bool] = True
  106. ):
  107. self.model = OAuth2Model(flows=flows, description=description)
  108. self.scheme_name = scheme_name or self.__class__.__name__
  109. self.auto_error = auto_error
  110. async def __call__(self, request: Request) -> Optional[str]:
  111. authorization: str = request.headers.get("Authorization")
  112. if not authorization:
  113. if self.auto_error:
  114. raise HTTPException(
  115. status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
  116. )
  117. else:
  118. return None
  119. return authorization
  120. class OAuth2PasswordBearer(OAuth2):
  121. def __init__(
  122. self,
  123. tokenUrl: str,
  124. scheme_name: Optional[str] = None,
  125. scopes: Optional[Dict[str, str]] = None,
  126. description: Optional[str] = None,
  127. auto_error: bool = True,
  128. ):
  129. if not scopes:
  130. scopes = {}
  131. flows = OAuthFlowsModel(password={"tokenUrl": tokenUrl, "scopes": scopes})
  132. super().__init__(
  133. flows=flows,
  134. scheme_name=scheme_name,
  135. description=description,
  136. auto_error=auto_error,
  137. )
  138. async def __call__(self, request: Request) -> Optional[str]:
  139. authorization: str = request.headers.get("Authorization")
  140. scheme, param = get_authorization_scheme_param(authorization)
  141. if not authorization or scheme.lower() != "bearer":
  142. if self.auto_error:
  143. raise HTTPException(
  144. status_code=HTTP_401_UNAUTHORIZED,
  145. detail="Not authenticated",
  146. headers={"WWW-Authenticate": "Bearer"},
  147. )
  148. else:
  149. return None
  150. return param
  151. class OAuth2AuthorizationCodeBearer(OAuth2):
  152. def __init__(
  153. self,
  154. authorizationUrl: str,
  155. tokenUrl: str,
  156. refreshUrl: Optional[str] = None,
  157. scheme_name: Optional[str] = None,
  158. scopes: Optional[Dict[str, str]] = None,
  159. description: Optional[str] = None,
  160. auto_error: bool = True,
  161. ):
  162. if not scopes:
  163. scopes = {}
  164. flows = OAuthFlowsModel(
  165. authorizationCode={
  166. "authorizationUrl": authorizationUrl,
  167. "tokenUrl": tokenUrl,
  168. "refreshUrl": refreshUrl,
  169. "scopes": scopes,
  170. }
  171. )
  172. super().__init__(
  173. flows=flows,
  174. scheme_name=scheme_name,
  175. description=description,
  176. auto_error=auto_error,
  177. )
  178. async def __call__(self, request: Request) -> Optional[str]:
  179. authorization: str = request.headers.get("Authorization")
  180. scheme, param = get_authorization_scheme_param(authorization)
  181. if not authorization or scheme.lower() != "bearer":
  182. if self.auto_error:
  183. raise HTTPException(
  184. status_code=HTTP_401_UNAUTHORIZED,
  185. detail="Not authenticated",
  186. headers={"WWW-Authenticate": "Bearer"},
  187. )
  188. else:
  189. return None # pragma: nocover
  190. return param
  191. class SecurityScopes:
  192. def __init__(self, scopes: Optional[List[str]] = None):
  193. self.scopes = scopes or []
  194. self.scope_str = " ".join(self.scopes)