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.
 
 
 
 

424 lines
13 KiB

  1. import binascii
  2. from base64 import b64decode
  3. from typing import Optional
  4. from fastapi.exceptions import HTTPException
  5. from fastapi.openapi.models import HTTPBase as HTTPBaseModel
  6. from fastapi.openapi.models import HTTPBearer as HTTPBearerModel
  7. from fastapi.security.base import SecurityBase
  8. from fastapi.security.utils import get_authorization_scheme_param
  9. from pydantic import BaseModel
  10. from starlette.requests import Request
  11. from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN
  12. from typing_extensions import Annotated, Doc
  13. class HTTPBasicCredentials(BaseModel):
  14. """
  15. The HTTP Basic credentials given as the result of using `HTTPBasic` in a
  16. dependency.
  17. Read more about it in the
  18. [FastAPI docs for HTTP Basic Auth](https://fastapi.tiangolo.com/advanced/security/http-basic-auth/).
  19. """
  20. username: Annotated[str, Doc("The HTTP Basic username.")]
  21. password: Annotated[str, Doc("The HTTP Basic password.")]
  22. class HTTPAuthorizationCredentials(BaseModel):
  23. """
  24. The HTTP authorization credentials in the result of using `HTTPBearer` or
  25. `HTTPDigest` in a dependency.
  26. The HTTP authorization header value is split by the first space.
  27. The first part is the `scheme`, the second part is the `credentials`.
  28. For example, in an HTTP Bearer token scheme, the client will send a header
  29. like:
  30. ```
  31. Authorization: Bearer deadbeef12346
  32. ```
  33. In this case:
  34. * `scheme` will have the value `"Bearer"`
  35. * `credentials` will have the value `"deadbeef12346"`
  36. """
  37. scheme: Annotated[
  38. str,
  39. Doc(
  40. """
  41. The HTTP authorization scheme extracted from the header value.
  42. """
  43. ),
  44. ]
  45. credentials: Annotated[
  46. str,
  47. Doc(
  48. """
  49. The HTTP authorization credentials extracted from the header value.
  50. """
  51. ),
  52. ]
  53. class HTTPBase(SecurityBase):
  54. def __init__(
  55. self,
  56. *,
  57. scheme: str,
  58. scheme_name: Optional[str] = None,
  59. description: Optional[str] = None,
  60. auto_error: bool = True,
  61. ):
  62. self.model = HTTPBaseModel(scheme=scheme, description=description)
  63. self.scheme_name = scheme_name or self.__class__.__name__
  64. self.auto_error = auto_error
  65. async def __call__(
  66. self, request: Request
  67. ) -> Optional[HTTPAuthorizationCredentials]:
  68. authorization = request.headers.get("Authorization")
  69. scheme, credentials = get_authorization_scheme_param(authorization)
  70. if not (authorization and scheme and credentials):
  71. if self.auto_error:
  72. raise HTTPException(
  73. status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
  74. )
  75. else:
  76. return None
  77. return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)
  78. class HTTPBasic(HTTPBase):
  79. """
  80. HTTP Basic authentication.
  81. ## Usage
  82. Create an instance object and use that object as the dependency in `Depends()`.
  83. The dependency result will be an `HTTPBasicCredentials` object containing the
  84. `username` and the `password`.
  85. Read more about it in the
  86. [FastAPI docs for HTTP Basic Auth](https://fastapi.tiangolo.com/advanced/security/http-basic-auth/).
  87. ## Example
  88. ```python
  89. from typing import Annotated
  90. from fastapi import Depends, FastAPI
  91. from fastapi.security import HTTPBasic, HTTPBasicCredentials
  92. app = FastAPI()
  93. security = HTTPBasic()
  94. @app.get("/users/me")
  95. def read_current_user(credentials: Annotated[HTTPBasicCredentials, Depends(security)]):
  96. return {"username": credentials.username, "password": credentials.password}
  97. ```
  98. """
  99. def __init__(
  100. self,
  101. *,
  102. scheme_name: Annotated[
  103. Optional[str],
  104. Doc(
  105. """
  106. Security scheme name.
  107. It will be included in the generated OpenAPI (e.g. visible at `/docs`).
  108. """
  109. ),
  110. ] = None,
  111. realm: Annotated[
  112. Optional[str],
  113. Doc(
  114. """
  115. HTTP Basic authentication realm.
  116. """
  117. ),
  118. ] = None,
  119. description: Annotated[
  120. Optional[str],
  121. Doc(
  122. """
  123. Security scheme description.
  124. It will be included in the generated OpenAPI (e.g. visible at `/docs`).
  125. """
  126. ),
  127. ] = None,
  128. auto_error: Annotated[
  129. bool,
  130. Doc(
  131. """
  132. By default, if the HTTP Basic authentication is not provided (a
  133. header), `HTTPBasic` will automatically cancel the request and send the
  134. client an error.
  135. If `auto_error` is set to `False`, when the HTTP Basic authentication
  136. is not available, instead of erroring out, the dependency result will
  137. be `None`.
  138. This is useful when you want to have optional authentication.
  139. It is also useful when you want to have authentication that can be
  140. provided in one of multiple optional ways (for example, in HTTP Basic
  141. authentication or in an HTTP Bearer token).
  142. """
  143. ),
  144. ] = True,
  145. ):
  146. self.model = HTTPBaseModel(scheme="basic", description=description)
  147. self.scheme_name = scheme_name or self.__class__.__name__
  148. self.realm = realm
  149. self.auto_error = auto_error
  150. async def __call__( # type: ignore
  151. self, request: Request
  152. ) -> Optional[HTTPBasicCredentials]:
  153. authorization = request.headers.get("Authorization")
  154. scheme, param = get_authorization_scheme_param(authorization)
  155. if self.realm:
  156. unauthorized_headers = {"WWW-Authenticate": f'Basic realm="{self.realm}"'}
  157. else:
  158. unauthorized_headers = {"WWW-Authenticate": "Basic"}
  159. if not authorization or scheme.lower() != "basic":
  160. if self.auto_error:
  161. raise HTTPException(
  162. status_code=HTTP_401_UNAUTHORIZED,
  163. detail="Not authenticated",
  164. headers=unauthorized_headers,
  165. )
  166. else:
  167. return None
  168. invalid_user_credentials_exc = HTTPException(
  169. status_code=HTTP_401_UNAUTHORIZED,
  170. detail="Invalid authentication credentials",
  171. headers=unauthorized_headers,
  172. )
  173. try:
  174. data = b64decode(param).decode("ascii")
  175. except (ValueError, UnicodeDecodeError, binascii.Error):
  176. raise invalid_user_credentials_exc # noqa: B904
  177. username, separator, password = data.partition(":")
  178. if not separator:
  179. raise invalid_user_credentials_exc
  180. return HTTPBasicCredentials(username=username, password=password)
  181. class HTTPBearer(HTTPBase):
  182. """
  183. HTTP Bearer token authentication.
  184. ## Usage
  185. Create an instance object and use that object as the dependency in `Depends()`.
  186. The dependency result will be an `HTTPAuthorizationCredentials` object containing
  187. the `scheme` and the `credentials`.
  188. ## Example
  189. ```python
  190. from typing import Annotated
  191. from fastapi import Depends, FastAPI
  192. from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
  193. app = FastAPI()
  194. security = HTTPBearer()
  195. @app.get("/users/me")
  196. def read_current_user(
  197. credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)]
  198. ):
  199. return {"scheme": credentials.scheme, "credentials": credentials.credentials}
  200. ```
  201. """
  202. def __init__(
  203. self,
  204. *,
  205. bearerFormat: Annotated[Optional[str], Doc("Bearer token format.")] = None,
  206. scheme_name: Annotated[
  207. Optional[str],
  208. Doc(
  209. """
  210. Security scheme name.
  211. It will be included in the generated OpenAPI (e.g. visible at `/docs`).
  212. """
  213. ),
  214. ] = None,
  215. description: Annotated[
  216. Optional[str],
  217. Doc(
  218. """
  219. Security scheme description.
  220. It will be included in the generated OpenAPI (e.g. visible at `/docs`).
  221. """
  222. ),
  223. ] = None,
  224. auto_error: Annotated[
  225. bool,
  226. Doc(
  227. """
  228. By default, if the HTTP Bearer token is not provided (in an
  229. `Authorization` header), `HTTPBearer` will automatically cancel the
  230. request and send the client an error.
  231. If `auto_error` is set to `False`, when the HTTP Bearer token
  232. is not available, instead of erroring out, the dependency result will
  233. be `None`.
  234. This is useful when you want to have optional authentication.
  235. It is also useful when you want to have authentication that can be
  236. provided in one of multiple optional ways (for example, in an HTTP
  237. Bearer token or in a cookie).
  238. """
  239. ),
  240. ] = True,
  241. ):
  242. self.model = HTTPBearerModel(bearerFormat=bearerFormat, description=description)
  243. self.scheme_name = scheme_name or self.__class__.__name__
  244. self.auto_error = auto_error
  245. async def __call__(
  246. self, request: Request
  247. ) -> Optional[HTTPAuthorizationCredentials]:
  248. authorization = request.headers.get("Authorization")
  249. scheme, credentials = get_authorization_scheme_param(authorization)
  250. if not (authorization and scheme and credentials):
  251. if self.auto_error:
  252. raise HTTPException(
  253. status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
  254. )
  255. else:
  256. return None
  257. if scheme.lower() != "bearer":
  258. if self.auto_error:
  259. raise HTTPException(
  260. status_code=HTTP_403_FORBIDDEN,
  261. detail="Invalid authentication credentials",
  262. )
  263. else:
  264. return None
  265. return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)
  266. class HTTPDigest(HTTPBase):
  267. """
  268. HTTP Digest authentication.
  269. ## Usage
  270. Create an instance object and use that object as the dependency in `Depends()`.
  271. The dependency result will be an `HTTPAuthorizationCredentials` object containing
  272. the `scheme` and the `credentials`.
  273. ## Example
  274. ```python
  275. from typing import Annotated
  276. from fastapi import Depends, FastAPI
  277. from fastapi.security import HTTPAuthorizationCredentials, HTTPDigest
  278. app = FastAPI()
  279. security = HTTPDigest()
  280. @app.get("/users/me")
  281. def read_current_user(
  282. credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)]
  283. ):
  284. return {"scheme": credentials.scheme, "credentials": credentials.credentials}
  285. ```
  286. """
  287. def __init__(
  288. self,
  289. *,
  290. scheme_name: Annotated[
  291. Optional[str],
  292. Doc(
  293. """
  294. Security scheme name.
  295. It will be included in the generated OpenAPI (e.g. visible at `/docs`).
  296. """
  297. ),
  298. ] = None,
  299. description: Annotated[
  300. Optional[str],
  301. Doc(
  302. """
  303. Security scheme description.
  304. It will be included in the generated OpenAPI (e.g. visible at `/docs`).
  305. """
  306. ),
  307. ] = None,
  308. auto_error: Annotated[
  309. bool,
  310. Doc(
  311. """
  312. By default, if the HTTP Digest is not provided, `HTTPDigest` will
  313. automatically cancel the request and send the client an error.
  314. If `auto_error` is set to `False`, when the HTTP Digest is not
  315. available, instead of erroring out, the dependency result will
  316. be `None`.
  317. This is useful when you want to have optional authentication.
  318. It is also useful when you want to have authentication that can be
  319. provided in one of multiple optional ways (for example, in HTTP
  320. Digest or in a cookie).
  321. """
  322. ),
  323. ] = True,
  324. ):
  325. self.model = HTTPBaseModel(scheme="digest", description=description)
  326. self.scheme_name = scheme_name or self.__class__.__name__
  327. self.auto_error = auto_error
  328. async def __call__(
  329. self, request: Request
  330. ) -> Optional[HTTPAuthorizationCredentials]:
  331. authorization = request.headers.get("Authorization")
  332. scheme, credentials = get_authorization_scheme_param(authorization)
  333. if not (authorization and scheme and credentials):
  334. if self.auto_error:
  335. raise HTTPException(
  336. status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
  337. )
  338. else:
  339. return None
  340. if scheme.lower() != "digest":
  341. if self.auto_error:
  342. raise HTTPException(
  343. status_code=HTTP_403_FORBIDDEN,
  344. detail="Invalid authentication credentials",
  345. )
  346. else:
  347. return None
  348. return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)