oauth2.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. from typing import Annotated, Any, cast
  2. from annotated_doc import Doc
  3. from fastapi.exceptions import HTTPException
  4. from fastapi.openapi.models import OAuth2 as OAuth2Model
  5. from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel
  6. from fastapi.param_functions import Form
  7. from fastapi.security.base import SecurityBase
  8. from fastapi.security.utils import get_authorization_scheme_param
  9. from starlette.requests import Request
  10. from starlette.status import HTTP_401_UNAUTHORIZED
  11. class OAuth2PasswordRequestForm:
  12. """
  13. This is a dependency class to collect the `username` and `password` as form data
  14. for an OAuth2 password flow.
  15. The OAuth2 specification dictates that for a password flow the data should be
  16. collected using form data (instead of JSON) and that it should have the specific
  17. fields `username` and `password`.
  18. All the initialization parameters are extracted from the request.
  19. Read more about it in the
  20. [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).
  21. ## Example
  22. ```python
  23. from typing import Annotated
  24. from fastapi import Depends, FastAPI
  25. from fastapi.security import OAuth2PasswordRequestForm
  26. app = FastAPI()
  27. @app.post("/login")
  28. def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):
  29. data = {}
  30. data["scopes"] = []
  31. for scope in form_data.scopes:
  32. data["scopes"].append(scope)
  33. if form_data.client_id:
  34. data["client_id"] = form_data.client_id
  35. if form_data.client_secret:
  36. data["client_secret"] = form_data.client_secret
  37. return data
  38. ```
  39. Note that for OAuth2 the scope `items:read` is a single scope in an opaque string.
  40. You could have custom internal logic to separate it by colon characters (`:`) or
  41. similar, and get the two parts `items` and `read`. Many applications do that to
  42. group and organize permissions, you could do it as well in your application, just
  43. know that it is application specific, it's not part of the specification.
  44. """
  45. def __init__(
  46. self,
  47. *,
  48. grant_type: Annotated[
  49. str | None,
  50. Form(pattern="^password$"),
  51. Doc(
  52. """
  53. The OAuth2 spec says it is required and MUST be the fixed string
  54. "password". Nevertheless, this dependency class is permissive and
  55. allows not passing it. If you want to enforce it, use instead the
  56. `OAuth2PasswordRequestFormStrict` dependency.
  57. Read more about it in the
  58. [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).
  59. """
  60. ),
  61. ] = None,
  62. username: Annotated[
  63. str,
  64. Form(),
  65. Doc(
  66. """
  67. `username` string. The OAuth2 spec requires the exact field name
  68. `username`.
  69. Read more about it in the
  70. [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).
  71. """
  72. ),
  73. ],
  74. password: Annotated[
  75. str,
  76. Form(json_schema_extra={"format": "password"}),
  77. Doc(
  78. """
  79. `password` string. The OAuth2 spec requires the exact field name
  80. `password`.
  81. Read more about it in the
  82. [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).
  83. """
  84. ),
  85. ],
  86. scope: Annotated[
  87. str,
  88. Form(),
  89. Doc(
  90. """
  91. A single string with actually several scopes separated by spaces. Each
  92. scope is also a string.
  93. For example, a single string with:
  94. ```python
  95. "items:read items:write users:read profile openid"
  96. ````
  97. would represent the scopes:
  98. * `items:read`
  99. * `items:write`
  100. * `users:read`
  101. * `profile`
  102. * `openid`
  103. Read more about it in the
  104. [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).
  105. """
  106. ),
  107. ] = "",
  108. client_id: Annotated[
  109. str | None,
  110. Form(),
  111. Doc(
  112. """
  113. If there's a `client_id`, it can be sent as part of the form fields.
  114. But the OAuth2 specification recommends sending the `client_id` and
  115. `client_secret` (if any) using HTTP Basic auth.
  116. """
  117. ),
  118. ] = None,
  119. client_secret: Annotated[
  120. str | None,
  121. Form(json_schema_extra={"format": "password"}),
  122. Doc(
  123. """
  124. If there's a `client_secret` (and a `client_id`), they can be sent
  125. as part of the form fields. But the OAuth2 specification recommends
  126. sending the `client_id` and `client_secret` (if any) using HTTP Basic
  127. auth.
  128. """
  129. ),
  130. ] = None,
  131. ):
  132. self.grant_type = grant_type
  133. self.username = username
  134. self.password = password
  135. self.scopes = scope.split()
  136. self.client_id = client_id
  137. self.client_secret = client_secret
  138. class OAuth2PasswordRequestFormStrict(OAuth2PasswordRequestForm):
  139. """
  140. This is a dependency class to collect the `username` and `password` as form data
  141. for an OAuth2 password flow.
  142. The OAuth2 specification dictates that for a password flow the data should be
  143. collected using form data (instead of JSON) and that it should have the specific
  144. fields `username` and `password`.
  145. All the initialization parameters are extracted from the request.
  146. The only difference between `OAuth2PasswordRequestFormStrict` and
  147. `OAuth2PasswordRequestForm` is that `OAuth2PasswordRequestFormStrict` requires the
  148. client to send the form field `grant_type` with the value `"password"`, which
  149. is required in the OAuth2 specification (it seems that for no particular reason),
  150. while for `OAuth2PasswordRequestForm` `grant_type` is optional.
  151. Read more about it in the
  152. [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).
  153. ## Example
  154. ```python
  155. from typing import Annotated
  156. from fastapi import Depends, FastAPI
  157. from fastapi.security import OAuth2PasswordRequestForm
  158. app = FastAPI()
  159. @app.post("/login")
  160. def login(form_data: Annotated[OAuth2PasswordRequestFormStrict, Depends()]):
  161. data = {}
  162. data["scopes"] = []
  163. for scope in form_data.scopes:
  164. data["scopes"].append(scope)
  165. if form_data.client_id:
  166. data["client_id"] = form_data.client_id
  167. if form_data.client_secret:
  168. data["client_secret"] = form_data.client_secret
  169. return data
  170. ```
  171. Note that for OAuth2 the scope `items:read` is a single scope in an opaque string.
  172. You could have custom internal logic to separate it by colon characters (`:`) or
  173. similar, and get the two parts `items` and `read`. Many applications do that to
  174. group and organize permissions, you could do it as well in your application, just
  175. know that it is application specific, it's not part of the specification.
  176. grant_type: the OAuth2 spec says it is required and MUST be the fixed string "password".
  177. This dependency is strict about it. If you want to be permissive, use instead the
  178. OAuth2PasswordRequestForm dependency class.
  179. username: username string. The OAuth2 spec requires the exact field name "username".
  180. password: password string. The OAuth2 spec requires the exact field name "password".
  181. scope: Optional string. Several scopes (each one a string) separated by spaces. E.g.
  182. "items:read items:write users:read profile openid"
  183. client_id: optional string. OAuth2 recommends sending the client_id and client_secret (if any)
  184. using HTTP Basic auth, as: client_id:client_secret
  185. client_secret: optional string. OAuth2 recommends sending the client_id and client_secret (if any)
  186. using HTTP Basic auth, as: client_id:client_secret
  187. """
  188. def __init__(
  189. self,
  190. grant_type: Annotated[
  191. str,
  192. Form(pattern="^password$"),
  193. Doc(
  194. """
  195. The OAuth2 spec says it is required and MUST be the fixed string
  196. "password". This dependency is strict about it. If you want to be
  197. permissive, use instead the `OAuth2PasswordRequestForm` dependency
  198. class.
  199. Read more about it in the
  200. [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).
  201. """
  202. ),
  203. ],
  204. username: Annotated[
  205. str,
  206. Form(),
  207. Doc(
  208. """
  209. `username` string. The OAuth2 spec requires the exact field name
  210. `username`.
  211. Read more about it in the
  212. [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).
  213. """
  214. ),
  215. ],
  216. password: Annotated[
  217. str,
  218. Form(),
  219. Doc(
  220. """
  221. `password` string. The OAuth2 spec requires the exact field name
  222. `password`.
  223. Read more about it in the
  224. [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).
  225. """
  226. ),
  227. ],
  228. scope: Annotated[
  229. str,
  230. Form(),
  231. Doc(
  232. """
  233. A single string with actually several scopes separated by spaces. Each
  234. scope is also a string.
  235. For example, a single string with:
  236. ```python
  237. "items:read items:write users:read profile openid"
  238. ````
  239. would represent the scopes:
  240. * `items:read`
  241. * `items:write`
  242. * `users:read`
  243. * `profile`
  244. * `openid`
  245. Read more about it in the
  246. [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).
  247. """
  248. ),
  249. ] = "",
  250. client_id: Annotated[
  251. str | None,
  252. Form(),
  253. Doc(
  254. """
  255. If there's a `client_id`, it can be sent as part of the form fields.
  256. But the OAuth2 specification recommends sending the `client_id` and
  257. `client_secret` (if any) using HTTP Basic auth.
  258. """
  259. ),
  260. ] = None,
  261. client_secret: Annotated[
  262. str | None,
  263. Form(),
  264. Doc(
  265. """
  266. If there's a `client_secret` (and a `client_id`), they can be sent
  267. as part of the form fields. But the OAuth2 specification recommends
  268. sending the `client_id` and `client_secret` (if any) using HTTP Basic
  269. auth.
  270. """
  271. ),
  272. ] = None,
  273. ):
  274. super().__init__(
  275. grant_type=grant_type,
  276. username=username,
  277. password=password,
  278. scope=scope,
  279. client_id=client_id,
  280. client_secret=client_secret,
  281. )
  282. class OAuth2(SecurityBase):
  283. """
  284. This is the base class for OAuth2 authentication, an instance of it would be used
  285. as a dependency. All other OAuth2 classes inherit from it and customize it for
  286. each OAuth2 flow.
  287. You normally would not create a new class inheriting from it but use one of the
  288. existing subclasses, and maybe compose them if you want to support multiple flows.
  289. Read more about it in the
  290. [FastAPI docs for Security](https://fastapi.tiangolo.com/tutorial/security/).
  291. """
  292. def __init__(
  293. self,
  294. *,
  295. flows: Annotated[
  296. OAuthFlowsModel | dict[str, dict[str, Any]],
  297. Doc(
  298. """
  299. The dictionary of OAuth2 flows.
  300. """
  301. ),
  302. ] = OAuthFlowsModel(),
  303. scheme_name: Annotated[
  304. str | None,
  305. Doc(
  306. """
  307. Security scheme name.
  308. It will be included in the generated OpenAPI (e.g. visible at `/docs`).
  309. """
  310. ),
  311. ] = None,
  312. description: Annotated[
  313. str | None,
  314. Doc(
  315. """
  316. Security scheme description.
  317. It will be included in the generated OpenAPI (e.g. visible at `/docs`).
  318. """
  319. ),
  320. ] = None,
  321. auto_error: Annotated[
  322. bool,
  323. Doc(
  324. """
  325. By default, if no HTTP Authorization header is provided, required for
  326. OAuth2 authentication, it will automatically cancel the request and
  327. send the client an error.
  328. If `auto_error` is set to `False`, when the HTTP Authorization header
  329. is not available, instead of erroring out, the dependency result will
  330. be `None`.
  331. This is useful when you want to have optional authentication.
  332. It is also useful when you want to have authentication that can be
  333. provided in one of multiple optional ways (for example, with OAuth2
  334. or in a cookie).
  335. """
  336. ),
  337. ] = True,
  338. ):
  339. self.model = OAuth2Model(
  340. flows=cast(OAuthFlowsModel, flows), description=description
  341. )
  342. self.scheme_name = scheme_name or self.__class__.__name__
  343. self.auto_error = auto_error
  344. def make_not_authenticated_error(self) -> HTTPException:
  345. """
  346. The OAuth 2 specification doesn't define the challenge that should be used,
  347. because a `Bearer` token is not really the only option to authenticate.
  348. But declaring any other authentication challenge would be application-specific
  349. as it's not defined in the specification.
  350. For practical reasons, this method uses the `Bearer` challenge by default, as
  351. it's probably the most common one.
  352. If you are implementing an OAuth2 authentication scheme other than the provided
  353. ones in FastAPI (based on bearer tokens), you might want to override this.
  354. Ref: https://datatracker.ietf.org/doc/html/rfc6749
  355. """
  356. return HTTPException(
  357. status_code=HTTP_401_UNAUTHORIZED,
  358. detail="Not authenticated",
  359. headers={"WWW-Authenticate": "Bearer"},
  360. )
  361. async def __call__(self, request: Request) -> str | None:
  362. authorization = request.headers.get("Authorization")
  363. if not authorization:
  364. if self.auto_error:
  365. raise self.make_not_authenticated_error()
  366. else:
  367. return None
  368. return authorization
  369. class OAuth2PasswordBearer(OAuth2):
  370. """
  371. OAuth2 flow for authentication using a bearer token obtained with a password.
  372. An instance of it would be used as a dependency.
  373. Read more about it in the
  374. [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).
  375. """
  376. def __init__(
  377. self,
  378. tokenUrl: Annotated[
  379. str,
  380. Doc(
  381. """
  382. The URL to obtain the OAuth2 token. This would be the *path operation*
  383. that has `OAuth2PasswordRequestForm` as a dependency.
  384. Read more about it in the
  385. [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).
  386. """
  387. ),
  388. ],
  389. scheme_name: Annotated[
  390. str | None,
  391. Doc(
  392. """
  393. Security scheme name.
  394. It will be included in the generated OpenAPI (e.g. visible at `/docs`).
  395. """
  396. ),
  397. ] = None,
  398. scopes: Annotated[
  399. dict[str, str] | None,
  400. Doc(
  401. """
  402. The OAuth2 scopes that would be required by the *path operations* that
  403. use this dependency.
  404. Read more about it in the
  405. [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).
  406. """
  407. ),
  408. ] = None,
  409. description: Annotated[
  410. str | None,
  411. Doc(
  412. """
  413. Security scheme description.
  414. It will be included in the generated OpenAPI (e.g. visible at `/docs`).
  415. """
  416. ),
  417. ] = None,
  418. auto_error: Annotated[
  419. bool,
  420. Doc(
  421. """
  422. By default, if no HTTP Authorization header is provided, required for
  423. OAuth2 authentication, it will automatically cancel the request and
  424. send the client an error.
  425. If `auto_error` is set to `False`, when the HTTP Authorization header
  426. is not available, instead of erroring out, the dependency result will
  427. be `None`.
  428. This is useful when you want to have optional authentication.
  429. It is also useful when you want to have authentication that can be
  430. provided in one of multiple optional ways (for example, with OAuth2
  431. or in a cookie).
  432. """
  433. ),
  434. ] = True,
  435. refreshUrl: Annotated[
  436. str | None,
  437. Doc(
  438. """
  439. The URL to refresh the token and obtain a new one.
  440. """
  441. ),
  442. ] = None,
  443. ):
  444. if not scopes:
  445. scopes = {}
  446. flows = OAuthFlowsModel(
  447. password=cast(
  448. Any,
  449. {
  450. "tokenUrl": tokenUrl,
  451. "refreshUrl": refreshUrl,
  452. "scopes": scopes,
  453. },
  454. )
  455. )
  456. super().__init__(
  457. flows=flows,
  458. scheme_name=scheme_name,
  459. description=description,
  460. auto_error=auto_error,
  461. )
  462. async def __call__(self, request: Request) -> str | None:
  463. authorization = request.headers.get("Authorization")
  464. scheme, param = get_authorization_scheme_param(authorization)
  465. if not authorization or scheme.lower() != "bearer":
  466. if self.auto_error:
  467. raise self.make_not_authenticated_error()
  468. else:
  469. return None
  470. return param
  471. class OAuth2AuthorizationCodeBearer(OAuth2):
  472. """
  473. OAuth2 flow for authentication using a bearer token obtained with an OAuth2 code
  474. flow. An instance of it would be used as a dependency.
  475. """
  476. def __init__(
  477. self,
  478. authorizationUrl: str,
  479. tokenUrl: Annotated[
  480. str,
  481. Doc(
  482. """
  483. The URL to obtain the OAuth2 token.
  484. """
  485. ),
  486. ],
  487. refreshUrl: Annotated[
  488. str | None,
  489. Doc(
  490. """
  491. The URL to refresh the token and obtain a new one.
  492. """
  493. ),
  494. ] = None,
  495. scheme_name: Annotated[
  496. str | None,
  497. Doc(
  498. """
  499. Security scheme name.
  500. It will be included in the generated OpenAPI (e.g. visible at `/docs`).
  501. """
  502. ),
  503. ] = None,
  504. scopes: Annotated[
  505. dict[str, str] | None,
  506. Doc(
  507. """
  508. The OAuth2 scopes that would be required by the *path operations* that
  509. use this dependency.
  510. """
  511. ),
  512. ] = None,
  513. description: Annotated[
  514. str | None,
  515. Doc(
  516. """
  517. Security scheme description.
  518. It will be included in the generated OpenAPI (e.g. visible at `/docs`).
  519. """
  520. ),
  521. ] = None,
  522. auto_error: Annotated[
  523. bool,
  524. Doc(
  525. """
  526. By default, if no HTTP Authorization header is provided, required for
  527. OAuth2 authentication, it will automatically cancel the request and
  528. send the client an error.
  529. If `auto_error` is set to `False`, when the HTTP Authorization header
  530. is not available, instead of erroring out, the dependency result will
  531. be `None`.
  532. This is useful when you want to have optional authentication.
  533. It is also useful when you want to have authentication that can be
  534. provided in one of multiple optional ways (for example, with OAuth2
  535. or in a cookie).
  536. """
  537. ),
  538. ] = True,
  539. ):
  540. if not scopes:
  541. scopes = {}
  542. flows = OAuthFlowsModel(
  543. authorizationCode=cast(
  544. Any,
  545. {
  546. "authorizationUrl": authorizationUrl,
  547. "tokenUrl": tokenUrl,
  548. "refreshUrl": refreshUrl,
  549. "scopes": scopes,
  550. },
  551. )
  552. )
  553. super().__init__(
  554. flows=flows,
  555. scheme_name=scheme_name,
  556. description=description,
  557. auto_error=auto_error,
  558. )
  559. async def __call__(self, request: Request) -> str | None:
  560. authorization = request.headers.get("Authorization")
  561. scheme, param = get_authorization_scheme_param(authorization)
  562. if not authorization or scheme.lower() != "bearer":
  563. if self.auto_error:
  564. raise self.make_not_authenticated_error()
  565. else:
  566. return None # pragma: nocover
  567. return param
  568. class SecurityScopes:
  569. """
  570. This is a special class that you can define in a parameter in a dependency to
  571. obtain the OAuth2 scopes required by all the dependencies in the same chain.
  572. This way, multiple dependencies can have different scopes, even when used in the
  573. same *path operation*. And with this, you can access all the scopes required in
  574. all those dependencies in a single place.
  575. Read more about it in the
  576. [FastAPI docs for OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/).
  577. """
  578. def __init__(
  579. self,
  580. scopes: Annotated[
  581. list[str] | None,
  582. Doc(
  583. """
  584. This will be filled by FastAPI.
  585. """
  586. ),
  587. ] = None,
  588. ):
  589. self.scopes: Annotated[
  590. list[str],
  591. Doc(
  592. """
  593. The list of all the scopes required by dependencies.
  594. """
  595. ),
  596. ] = scopes or []
  597. self.scope_str: Annotated[
  598. str,
  599. Doc(
  600. """
  601. All the scopes required by all the dependencies in a single string
  602. separated by spaces, as defined in the OAuth2 specification.
  603. """
  604. ),
  605. ] = " ".join(self.scopes)