Security Tools

When you need to declare dependencies with OAuth2 scopes you use Security().

But you still need to define what is the dependable, the callable that you pass as a parameter to Depends() or Security().

There are multiple tools that you can use to create those dependables, and they get integrated into OpenAPI so they are shown in the automatic docs UI, they can be used by automatically generated clients and SDKs, etc.

You can import them from fastapi.security:

  1. from fastapi.security import (
  2. APIKeyCookie,
  3. APIKeyHeader,
  4. APIKeyQuery,
  5. HTTPAuthorizationCredentials,
  6. HTTPBasic,
  7. HTTPBasicCredentials,
  8. HTTPBearer,
  9. HTTPDigest,
  10. OAuth2,
  11. OAuth2AuthorizationCodeBearer,
  12. OAuth2PasswordBearer,
  13. OAuth2PasswordRequestForm,
  14. OAuth2PasswordRequestFormStrict,
  15. OpenIdConnect,
  16. SecurityScopes,
  17. )

API Key Security Schemes

fastapi.security.APIKeyCookie

  1. APIKeyCookie(
  2. *,
  3. name,
  4. scheme_name=None,
  5. description=None,
  6. auto_error=True
  7. )

Bases: APIKeyBase

API key authentication using a cookie.

This defines the name of the cookie that should be provided in the request with the API key and integrates that into the OpenAPI documentation. It extracts the key value sent in the cookie automatically and provides it as the dependency result. But it doesn’t define how to set that cookie.

Usage

Create an instance object and use that object as the dependency in Depends().

The dependency result will be a string containing the key value.

Example

  1. from fastapi import Depends, FastAPI
  2. from fastapi.security import APIKeyCookie
  3. app = FastAPI()
  4. cookie_scheme = APIKeyCookie(name="session")
  5. @app.get("/items/")
  6. async def read_items(session: str = Depends(cookie_scheme)):
  7. return {"session": session}
PARAMETERDESCRIPTION
name

Cookie name.

TYPE: str

scheme_name

Security scheme name.

It will be included in the generated OpenAPI (e.g. visible at /docs).

TYPE: Optional[str] DEFAULT: None

description

Security scheme description.

It will be included in the generated OpenAPI (e.g. visible at /docs).

TYPE: Optional[str] DEFAULT: None

auto_error

By default, if the cookie is not provided, APIKeyCookie will automatically cancel the request and send the client an error.

If auto_error is set to False, when the cookie is not available, instead of erroring out, the dependency result will be None.

This is useful when you want to have optional authentication.

It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in a cookie or in an HTTP Bearer token).

TYPE: bool DEFAULT: True

Source code in fastapi/security/api_key.py

  1. 241
  2. 242
  3. 243
  4. 244
  5. 245
  6. 246
  7. 247
  8. 248
  9. 249
  10. 250
  11. 251
  12. 252
  13. 253
  14. 254
  15. 255
  16. 256
  17. 257
  18. 258
  19. 259
  20. 260
  21. 261
  22. 262
  23. 263
  24. 264
  25. 265
  26. 266
  27. 267
  28. 268
  29. 269
  30. 270
  31. 271
  32. 272
  33. 273
  34. 274
  35. 275
  36. 276
  37. 277
  38. 278
  39. 279
  40. 280
  41. 281
  42. 282
  43. 283
  44. 284
  45. 285
  46. 286
  47. 287
  48. 288
  49. 289
  50. 290
  1. def init(
  2. self,
  3. ,
  4. name: Annotated[str, Doc(Cookie name.”)],
  5. scheme_name: Annotated[
  6. Optional[str],
  7. Doc(
  8. “””
  9. Security scheme name.
  10. It will be included in the generated OpenAPI (e.g. visible at /docs).
  11. “””
  12. ),
  13. ] = None,
  14. description: Annotated[
  15. Optional[str],
  16. Doc(
  17. “””
  18. Security scheme description.
  19. It will be included in the generated OpenAPI (e.g. visible at /docs).
  20. “””
  21. ),
  22. ] = None,
  23. auto_error: Annotated[
  24. bool,
  25. Doc(
  26. “””
  27. By default, if the cookie is not provided, APIKeyCookie will
  28. automatically cancel the request and send the client an error.
  29. If auto_error is set to False, when the cookie is not available,
  30. instead of erroring out, the dependency result will be None.
  31. This is useful when you want to have optional authentication.
  32. It is also useful when you want to have authentication that can be
  33. provided in one of multiple optional ways (for example, in a cookie or
  34. in an HTTP Bearer token).
  35. “””
  36. ),
  37. ] = True,
  38. ):
  39. self.model: APIKey = APIKey(
  40. *{in: APIKeyIn.cookie}, # type: ignore[arg-type]
  41. name=name,
  42. description=description,
  43. )
  44. self.schemename = schemename or self.class.__name
  45. self.auto_error = auto_error

model instance-attribute

  1. model = APIKey(
  2. **{"in": cookie}, name=name, description=description
  3. )

scheme_name instance-attribute

  1. scheme_name = scheme_name or __name__

auto_error instance-attribute

  1. auto_error = auto_error

fastapi.security.APIKeyHeader

  1. APIKeyHeader(
  2. *,
  3. name,
  4. scheme_name=None,
  5. description=None,
  6. auto_error=True
  7. )

Bases: APIKeyBase

API key authentication using a header.

This defines the name of the header that should be provided in the request with the API key and integrates that into the OpenAPI documentation. It extracts the key value sent in the header automatically and provides it as the dependency result. But it doesn’t define how to send that key to the client.

Usage

Create an instance object and use that object as the dependency in Depends().

The dependency result will be a string containing the key value.

Example

  1. from fastapi import Depends, FastAPI
  2. from fastapi.security import APIKeyHeader
  3. app = FastAPI()
  4. header_scheme = APIKeyHeader(name="x-key")
  5. @app.get("/items/")
  6. async def read_items(key: str = Depends(header_scheme)):
  7. return {"key": key}
PARAMETERDESCRIPTION
name

Header name.

TYPE: str

scheme_name

Security scheme name.

It will be included in the generated OpenAPI (e.g. visible at /docs).

TYPE: Optional[str] DEFAULT: None

description

Security scheme description.

It will be included in the generated OpenAPI (e.g. visible at /docs).

TYPE: Optional[str] DEFAULT: None

auto_error

By default, if the header is not provided, APIKeyHeader will automatically cancel the request and send the client an error.

If auto_error is set to False, when the header is not available, instead of erroring out, the dependency result will be None.

This is useful when you want to have optional authentication.

It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in a header or in an HTTP Bearer token).

TYPE: bool DEFAULT: True

Source code in fastapi/security/api_key.py

  1. 146
  2. 147
  3. 148
  4. 149
  5. 150
  6. 151
  7. 152
  8. 153
  9. 154
  10. 155
  11. 156
  12. 157
  13. 158
  14. 159
  15. 160
  16. 161
  17. 162
  18. 163
  19. 164
  20. 165
  21. 166
  22. 167
  23. 168
  24. 169
  25. 170
  26. 171
  27. 172
  28. 173
  29. 174
  30. 175
  31. 176
  32. 177
  33. 178
  34. 179
  35. 180
  36. 181
  37. 182
  38. 183
  39. 184
  40. 185
  41. 186
  42. 187
  43. 188
  44. 189
  45. 190
  46. 191
  47. 192
  48. 193
  49. 194
  50. 195
  1. def init(
  2. self,
  3. ,
  4. name: Annotated[str, Doc(Header name.”)],
  5. scheme_name: Annotated[
  6. Optional[str],
  7. Doc(
  8. “””
  9. Security scheme name.
  10. It will be included in the generated OpenAPI (e.g. visible at /docs).
  11. “””
  12. ),
  13. ] = None,
  14. description: Annotated[
  15. Optional[str],
  16. Doc(
  17. “””
  18. Security scheme description.
  19. It will be included in the generated OpenAPI (e.g. visible at /docs).
  20. “””
  21. ),
  22. ] = None,
  23. auto_error: Annotated[
  24. bool,
  25. Doc(
  26. “””
  27. By default, if the header is not provided, APIKeyHeader will
  28. automatically cancel the request and send the client an error.
  29. If auto_error is set to False, when the header is not available,
  30. instead of erroring out, the dependency result will be None.
  31. This is useful when you want to have optional authentication.
  32. It is also useful when you want to have authentication that can be
  33. provided in one of multiple optional ways (for example, in a header or
  34. in an HTTP Bearer token).
  35. “””
  36. ),
  37. ] = True,
  38. ):
  39. self.model: APIKey = APIKey(
  40. *{in: APIKeyIn.header}, # type: ignore[arg-type]
  41. name=name,
  42. description=description,
  43. )
  44. self.schemename = schemename or self.class.__name
  45. self.auto_error = auto_error

model instance-attribute

  1. model = APIKey(
  2. **{"in": header}, name=name, description=description
  3. )

scheme_name instance-attribute

  1. scheme_name = scheme_name or __name__

auto_error instance-attribute

  1. auto_error = auto_error

fastapi.security.APIKeyQuery

  1. APIKeyQuery(
  2. *,
  3. name,
  4. scheme_name=None,
  5. description=None,
  6. auto_error=True
  7. )

Bases: APIKeyBase

API key authentication using a query parameter.

This defines the name of the query parameter that should be provided in the request with the API key and integrates that into the OpenAPI documentation. It extracts the key value sent in the query parameter automatically and provides it as the dependency result. But it doesn’t define how to send that API key to the client.

Usage

Create an instance object and use that object as the dependency in Depends().

The dependency result will be a string containing the key value.

Example

  1. from fastapi import Depends, FastAPI
  2. from fastapi.security import APIKeyQuery
  3. app = FastAPI()
  4. query_scheme = APIKeyQuery(name="api_key")
  5. @app.get("/items/")
  6. async def read_items(api_key: str = Depends(query_scheme)):
  7. return {"api_key": api_key}
PARAMETERDESCRIPTION
name

Query parameter name.

TYPE: str

scheme_name

Security scheme name.

It will be included in the generated OpenAPI (e.g. visible at /docs).

TYPE: Optional[str] DEFAULT: None

description

Security scheme description.

It will be included in the generated OpenAPI (e.g. visible at /docs).

TYPE: Optional[str] DEFAULT: None

auto_error

By default, if the query parameter is not provided, APIKeyQuery will automatically cancel the request and sebd the client an error.

If auto_error is set to False, when the query parameter is not available, instead of erroring out, the dependency result will be None.

This is useful when you want to have optional authentication.

It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in a query parameter or in an HTTP Bearer token).

TYPE: bool DEFAULT: True

Source code in fastapi/security/api_key.py

  1. 47
  2. 48
  3. 49
  4. 50
  5. 51
  6. 52
  7. 53
  8. 54
  9. 55
  10. 56
  11. 57
  12. 58
  13. 59
  14. 60
  15. 61
  16. 62
  17. 63
  18. 64
  19. 65
  20. 66
  21. 67
  22. 68
  23. 69
  24. 70
  25. 71
  26. 72
  27. 73
  28. 74
  29. 75
  30. 76
  31. 77
  32. 78
  33. 79
  34. 80
  35. 81
  36. 82
  37. 83
  38. 84
  39. 85
  40. 86
  41. 87
  42. 88
  43. 89
  44. 90
  45. 91
  46. 92
  47. 93
  48. 94
  49. 95
  50. 96
  51. 97
  52. 98
  53. 99
  54. 100
  1. def init(
  2. self,
  3. ,
  4. name: Annotated[
  5. str,
  6. Doc(Query parameter name.”),
  7. ],
  8. scheme_name: Annotated[
  9. Optional[str],
  10. Doc(
  11. “””
  12. Security scheme name.
  13. It will be included in the generated OpenAPI (e.g. visible at /docs).
  14. “””
  15. ),
  16. ] = None,
  17. description: Annotated[
  18. Optional[str],
  19. Doc(
  20. “””
  21. Security scheme description.
  22. It will be included in the generated OpenAPI (e.g. visible at /docs).
  23. “””
  24. ),
  25. ] = None,
  26. auto_error: Annotated[
  27. bool,
  28. Doc(
  29. “””
  30. By default, if the query parameter is not provided, APIKeyQuery will
  31. automatically cancel the request and sebd the client an error.
  32. If auto_error is set to False, when the query parameter is not
  33. available, instead of erroring out, the dependency result will be
  34. None.
  35. This is useful when you want to have optional authentication.
  36. It is also useful when you want to have authentication that can be
  37. provided in one of multiple optional ways (for example, in a query
  38. parameter or in an HTTP Bearer token).
  39. “””
  40. ),
  41. ] = True,
  42. ):
  43. self.model: APIKey = APIKey(
  44. *{in: APIKeyIn.query}, # type: ignore[arg-type]
  45. name=name,
  46. description=description,
  47. )
  48. self.schemename = schemename or self.class.__name
  49. self.auto_error = auto_error

model instance-attribute

  1. model = APIKey(
  2. **{"in": query}, name=name, description=description
  3. )

scheme_name instance-attribute

  1. scheme_name = scheme_name or __name__

auto_error instance-attribute

  1. auto_error = auto_error

HTTP Authentication Schemes

fastapi.security.HTTPBasic

  1. HTTPBasic(
  2. *,
  3. scheme_name=None,
  4. realm=None,
  5. description=None,
  6. auto_error=True
  7. )

Bases: HTTPBase

HTTP Basic authentication.

Usage

Create an instance object and use that object as the dependency in Depends().

The dependency result will be an HTTPBasicCredentials object containing the username and the password.

Read more about it in the FastAPI docs for HTTP Basic Auth.

Example

  1. from typing import Annotated
  2. from fastapi import Depends, FastAPI
  3. from fastapi.security import HTTPBasic, HTTPBasicCredentials
  4. app = FastAPI()
  5. security = HTTPBasic()
  6. @app.get("/users/me")
  7. def read_current_user(credentials: Annotated[HTTPBasicCredentials, Depends(security)]):
  8. return {"username": credentials.username, "password": credentials.password}
PARAMETERDESCRIPTION
scheme_name

Security scheme name.

It will be included in the generated OpenAPI (e.g. visible at /docs).

TYPE: Optional[str] DEFAULT: None

realm

HTTP Basic authentication realm.

TYPE: Optional[str] DEFAULT: None

description

Security scheme description.

It will be included in the generated OpenAPI (e.g. visible at /docs).

TYPE: Optional[str] DEFAULT: None

auto_error

By default, if the HTTP Basic authentication is not provided (a header), HTTPBasic will automatically cancel the request and send the client an error.

If auto_error is set to False, when the HTTP Basic authentication is not available, instead of erroring out, the dependency result will be None.

This is useful when you want to have optional authentication.

It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in HTTP Basic authentication or in an HTTP Bearer token).

TYPE: bool DEFAULT: True

Source code in fastapi/security/http.py

  1. 130
  2. 131
  3. 132
  4. 133
  5. 134
  6. 135
  7. 136
  8. 137
  9. 138
  10. 139
  11. 140
  12. 141
  13. 142
  14. 143
  15. 144
  16. 145
  17. 146
  18. 147
  19. 148
  20. 149
  21. 150
  22. 151
  23. 152
  24. 153
  25. 154
  26. 155
  27. 156
  28. 157
  29. 158
  30. 159
  31. 160
  32. 161
  33. 162
  34. 163
  35. 164
  36. 165
  37. 166
  38. 167
  39. 168
  40. 169
  41. 170
  42. 171
  43. 172
  44. 173
  45. 174
  46. 175
  47. 176
  48. 177
  49. 178
  50. 179
  51. 180
  52. 181
  53. 182
  54. 183
  55. 184
  56. 185
  1. def init(
  2. self,
  3. *,
  4. schemename: Annotated[
  5. Optional[str],
  6. Doc(
  7. “””
  8. Security scheme name.
  9. It will be included in the generated OpenAPI (e.g. visible at /docs).
  10. “””
  11. ),
  12. ] = None,
  13. realm: Annotated[
  14. Optional[str],
  15. Doc(
  16. “””
  17. HTTP Basic authentication realm.
  18. “””
  19. ),
  20. ] = None,
  21. description: Annotated[
  22. Optional[str],
  23. Doc(
  24. “””
  25. Security scheme description.
  26. It will be included in the generated OpenAPI (e.g. visible at /docs).
  27. “””
  28. ),
  29. ] = None,
  30. autoerror: Annotated[
  31. bool,
  32. Doc(
  33. “””
  34. By default, if the HTTP Basic authentication is not provided (a
  35. header), HTTPBasic will automatically cancel the request and send the
  36. client an error.
  37. If auto_error is set to False, when the HTTP Basic authentication
  38. is not available, instead of erroring out, the dependency result will
  39. be None.
  40. This is useful when you want to have optional authentication.
  41. It is also useful when you want to have authentication that can be
  42. provided in one of multiple optional ways (for example, in HTTP Basic
  43. authentication or in an HTTP Bearer token).
  44. “””
  45. ),
  46. ] = True,
  47. ):
  48. self.model = HTTPBaseModel(scheme=basic, description=description)
  49. self.schemename = schemename or self.__class.__name
  50. self.realm = realm
  51. self.auto_error = auto_error

model instance-attribute

  1. model = HTTPBase(scheme='basic', description=description)

scheme_name instance-attribute

  1. scheme_name = scheme_name or __name__

realm instance-attribute

  1. realm = realm

auto_error instance-attribute

  1. auto_error = auto_error

fastapi.security.HTTPBearer

  1. HTTPBearer(
  2. *,
  3. bearerFormat=None,
  4. scheme_name=None,
  5. description=None,
  6. auto_error=True
  7. )

Bases: HTTPBase

HTTP Bearer token authentication.

Usage

Create an instance object and use that object as the dependency in Depends().

The dependency result will be an HTTPAuthorizationCredentials object containing the scheme and the credentials.

Example

  1. from typing import Annotated
  2. from fastapi import Depends, FastAPI
  3. from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
  4. app = FastAPI()
  5. security = HTTPBearer()
  6. @app.get("/users/me")
  7. def read_current_user(
  8. credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)]
  9. ):
  10. return {"scheme": credentials.scheme, "credentials": credentials.credentials}
PARAMETERDESCRIPTION
bearerFormat

Bearer token format.

TYPE: Optional[str] DEFAULT: None

scheme_name

Security scheme name.

It will be included in the generated OpenAPI (e.g. visible at /docs).

TYPE: Optional[str] DEFAULT: None

description

Security scheme description.

It will be included in the generated OpenAPI (e.g. visible at /docs).

TYPE: Optional[str] DEFAULT: None

auto_error

By default, if the HTTP Bearer token not provided (in an Authorization header), HTTPBearer will automatically cancel the request and send the client an error.

If auto_error is set to False, when the HTTP Bearer token is not available, instead of erroring out, the dependency result will be None.

This is useful when you want to have optional authentication.

It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in an HTTP Bearer token or in a cookie).

TYPE: bool DEFAULT: True

Source code in fastapi/security/http.py

  1. 252
  2. 253
  3. 254
  4. 255
  5. 256
  6. 257
  7. 258
  8. 259
  9. 260
  10. 261
  11. 262
  12. 263
  13. 264
  14. 265
  15. 266
  16. 267
  17. 268
  18. 269
  19. 270
  20. 271
  21. 272
  22. 273
  23. 274
  24. 275
  25. 276
  26. 277
  27. 278
  28. 279
  29. 280
  30. 281
  31. 282
  32. 283
  33. 284
  34. 285
  35. 286
  36. 287
  37. 288
  38. 289
  39. 290
  40. 291
  41. 292
  42. 293
  43. 294
  44. 295
  45. 296
  46. 297
  47. 298
  48. 299
  1. def init(
  2. self,
  3. *,
  4. bearerFormat: Annotated[Optional[str], Doc(Bearer token format.”)] = None,
  5. schemename: Annotated[
  6. Optional[str],
  7. Doc(
  8. “””
  9. Security scheme name.
  10. It will be included in the generated OpenAPI (e.g. visible at /docs).
  11. “””
  12. ),
  13. ] = None,
  14. description: Annotated[
  15. Optional[str],
  16. Doc(
  17. “””
  18. Security scheme description.
  19. It will be included in the generated OpenAPI (e.g. visible at /docs).
  20. “””
  21. ),
  22. ] = None,
  23. autoerror: Annotated[
  24. bool,
  25. Doc(
  26. “””
  27. By default, if the HTTP Bearer token not provided (in an
  28. Authorization header), HTTPBearer will automatically cancel the
  29. request and send the client an error.
  30. If auto_error is set to False, when the HTTP Bearer token
  31. is not available, instead of erroring out, the dependency result will
  32. be None.
  33. This is useful when you want to have optional authentication.
  34. It is also useful when you want to have authentication that can be
  35. provided in one of multiple optional ways (for example, in an HTTP
  36. Bearer token or in a cookie).
  37. “””
  38. ),
  39. ] = True,
  40. ):
  41. self.model = HTTPBearerModel(bearerFormat=bearerFormat, description=description)
  42. self.schemename = schemename or self.__class.__name
  43. self.auto_error = auto_error

model instance-attribute

  1. model = HTTPBearer(
  2. bearerFormat=bearerFormat, description=description
  3. )

scheme_name instance-attribute

  1. scheme_name = scheme_name or __name__

auto_error instance-attribute

  1. auto_error = auto_error

fastapi.security.HTTPDigest

  1. HTTPDigest(
  2. *, scheme_name=None, description=None, auto_error=True
  3. )

Bases: HTTPBase

HTTP Digest authentication.

Usage

Create an instance object and use that object as the dependency in Depends().

The dependency result will be an HTTPAuthorizationCredentials object containing the scheme and the credentials.

Example

  1. from typing import Annotated
  2. from fastapi import Depends, FastAPI
  3. from fastapi.security import HTTPAuthorizationCredentials, HTTPDigest
  4. app = FastAPI()
  5. security = HTTPDigest()
  6. @app.get("/users/me")
  7. def read_current_user(
  8. credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)]
  9. ):
  10. return {"scheme": credentials.scheme, "credentials": credentials.credentials}
PARAMETERDESCRIPTION
scheme_name

Security scheme name.

It will be included in the generated OpenAPI (e.g. visible at /docs).

TYPE: Optional[str] DEFAULT: None

description

Security scheme description.

It will be included in the generated OpenAPI (e.g. visible at /docs).

TYPE: Optional[str] DEFAULT: None

auto_error

By default, if the HTTP Digest not provided, HTTPDigest will automatically cancel the request and send the client an error.

If auto_error is set to False, when the HTTP Digest is not available, instead of erroring out, the dependency result will be None.

This is useful when you want to have optional authentication.

It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in HTTP Digest or in a cookie).

TYPE: bool DEFAULT: True

Source code in fastapi/security/http.py

  1. 356
  2. 357
  3. 358
  4. 359
  5. 360
  6. 361
  7. 362
  8. 363
  9. 364
  10. 365
  11. 366
  12. 367
  13. 368
  14. 369
  15. 370
  16. 371
  17. 372
  18. 373
  19. 374
  20. 375
  21. 376
  22. 377
  23. 378
  24. 379
  25. 380
  26. 381
  27. 382
  28. 383
  29. 384
  30. 385
  31. 386
  32. 387
  33. 388
  34. 389
  35. 390
  36. 391
  37. 392
  38. 393
  39. 394
  40. 395
  41. 396
  42. 397
  43. 398
  44. 399
  45. 400
  46. 401
  1. def init(
  2. self,
  3. *,
  4. schemename: Annotated[
  5. Optional[str],
  6. Doc(
  7. “””
  8. Security scheme name.
  9. It will be included in the generated OpenAPI (e.g. visible at /docs).
  10. “””
  11. ),
  12. ] = None,
  13. description: Annotated[
  14. Optional[str],
  15. Doc(
  16. “””
  17. Security scheme description.
  18. It will be included in the generated OpenAPI (e.g. visible at /docs).
  19. “””
  20. ),
  21. ] = None,
  22. autoerror: Annotated[
  23. bool,
  24. Doc(
  25. “””
  26. By default, if the HTTP Digest not provided, HTTPDigest will
  27. automatically cancel the request and send the client an error.
  28. If auto_error is set to False, when the HTTP Digest is not
  29. available, instead of erroring out, the dependency result will
  30. be None.
  31. This is useful when you want to have optional authentication.
  32. It is also useful when you want to have authentication that can be
  33. provided in one of multiple optional ways (for example, in HTTP
  34. Digest or in a cookie).
  35. “””
  36. ),
  37. ] = True,
  38. ):
  39. self.model = HTTPBaseModel(scheme=digest, description=description)
  40. self.schemename = schemename or self.__class.__name
  41. self.auto_error = auto_error

model instance-attribute

  1. model = HTTPBase(scheme='digest', description=description)

scheme_name instance-attribute

  1. scheme_name = scheme_name or __name__

auto_error instance-attribute

  1. auto_error = auto_error

HTTP Credentials

fastapi.security.HTTPAuthorizationCredentials

Bases: BaseModel

The HTTP authorization credentials in the result of using HTTPBearer or HTTPDigest in a dependency.

The HTTP authorization header value is split by the first space.

The first part is the scheme, the second part is the credentials.

For example, in an HTTP Bearer token scheme, the client will send a header like:

  1. Authorization: Bearer deadbeef12346

In this case:

  • scheme will have the value "Bearer"
  • credentials will have the value "deadbeef12346"

scheme instance-attribute

  1. scheme

The HTTP authorization scheme extracted from the header value.

credentials instance-attribute

  1. credentials

The HTTP authorization credentials extracted from the header value.

fastapi.security.HTTPBasicCredentials

Bases: BaseModel

The HTTP Basic credendials given as the result of using HTTPBasic in a dependency.

Read more about it in the FastAPI docs for HTTP Basic Auth.

username instance-attribute

  1. username

The HTTP Basic username.

password instance-attribute

  1. password

The HTTP Basic password.

OAuth2 Authentication

fastapi.security.OAuth2

  1. OAuth2(
  2. *,
  3. flows=OAuthFlowsModel(),
  4. scheme_name=None,
  5. description=None,
  6. auto_error=True
  7. )

Bases: SecurityBase

This is the base class for OAuth2 authentication, an instance of it would be used as a dependency. All other OAuth2 classes inherit from it and customize it for each OAuth2 flow.

You normally would not create a new class inheriting from it but use one of the existing subclasses, and maybe compose them if you want to support multiple flows.

Read more about it in the FastAPI docs for Security.

PARAMETERDESCRIPTION
flows

The dictionary of OAuth2 flows.

TYPE: Union[OAuthFlows, Dict[str, Dict[str, Any]]] DEFAULT: OAuthFlows()

scheme_name

Security scheme name.

It will be included in the generated OpenAPI (e.g. visible at /docs).

TYPE: Optional[str] DEFAULT: None

description

Security scheme description.

It will be included in the generated OpenAPI (e.g. visible at /docs).

TYPE: Optional[str] DEFAULT: None

auto_error

By default, if no HTTP Auhtorization header is provided, required for OAuth2 authentication, it will automatically cancel the request and send the client an error.

If auto_error is set to False, when the HTTP Authorization header is not available, instead of erroring out, the dependency result will be None.

This is useful when you want to have optional authentication.

It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, with OAuth2 or in a cookie).

TYPE: bool DEFAULT: True

Source code in fastapi/security/oauth2.py

  1. 321
  2. 322
  3. 323
  4. 324
  5. 325
  6. 326
  7. 327
  8. 328
  9. 329
  10. 330
  11. 331
  12. 332
  13. 333
  14. 334
  15. 335
  16. 336
  17. 337
  18. 338
  19. 339
  20. 340
  21. 341
  22. 342
  23. 343
  24. 344
  25. 345
  26. 346
  27. 347
  28. 348
  29. 349
  30. 350
  31. 351
  32. 352
  33. 353
  34. 354
  35. 355
  36. 356
  37. 357
  38. 358
  39. 359
  40. 360
  41. 361
  42. 362
  43. 363
  44. 364
  45. 365
  46. 366
  47. 367
  48. 368
  49. 369
  50. 370
  51. 371
  52. 372
  53. 373
  54. 374
  55. 375
  56. 376
  57. 377
  1. def init(
  2. self,
  3. *,
  4. flows: Annotated[
  5. Union[OAuthFlowsModel, Dict[str, Dict[str, Any]]],
  6. Doc(
  7. “””
  8. The dictionary of OAuth2 flows.
  9. “””
  10. ),
  11. ] = OAuthFlowsModel(),
  12. schemename: Annotated[
  13. Optional[str],
  14. Doc(
  15. “””
  16. Security scheme name.
  17. It will be included in the generated OpenAPI (e.g. visible at /docs).
  18. “””
  19. ),
  20. ] = None,
  21. description: Annotated[
  22. Optional[str],
  23. Doc(
  24. “””
  25. Security scheme description.
  26. It will be included in the generated OpenAPI (e.g. visible at /docs).
  27. “””
  28. ),
  29. ] = None,
  30. autoerror: Annotated[
  31. bool,
  32. Doc(
  33. “””
  34. By default, if no HTTP Auhtorization header is provided, required for
  35. OAuth2 authentication, it will automatically cancel the request and
  36. send the client an error.
  37. If auto_error is set to False, when the HTTP Authorization header
  38. is not available, instead of erroring out, the dependency result will
  39. be None.
  40. This is useful when you want to have optional authentication.
  41. It is also useful when you want to have authentication that can be
  42. provided in one of multiple optional ways (for example, with OAuth2
  43. or in a cookie).
  44. “””
  45. ),
  46. ] = True,
  47. ):
  48. self.model = OAuth2Model(
  49. flows=cast(OAuthFlowsModel, flows), description=description
  50. )
  51. self.schemename = schemename or self.__class.__name
  52. self.auto_error = auto_error

model instance-attribute

  1. model = OAuth2(
  2. flows=cast(OAuthFlows, flows), description=description
  3. )

scheme_name instance-attribute

  1. scheme_name = scheme_name or __name__

auto_error instance-attribute

  1. auto_error = auto_error

fastapi.security.OAuth2AuthorizationCodeBearer

  1. OAuth2AuthorizationCodeBearer(
  2. authorizationUrl,
  3. tokenUrl,
  4. refreshUrl=None,
  5. scheme_name=None,
  6. scopes=None,
  7. description=None,
  8. auto_error=True,
  9. )

Bases: [OAuth2](#fastapi.security.OAuth2 "fastapi.security.oauth2.OAuth2")

OAuth2 flow for authentication using a bearer token obtained with an OAuth2 code flow. An instance of it would be used as a dependency.

PARAMETERDESCRIPTION
authorizationUrl

TYPE: str

tokenUrl

The URL to obtain the OAuth2 token.

TYPE: str

refreshUrl

The URL to refresh the token and obtain a new one.

TYPE: Optional[str] DEFAULT: None

scheme_name

Security scheme name.

It will be included in the generated OpenAPI (e.g. visible at /docs).

TYPE: Optional[str] DEFAULT: None

scopes

The OAuth2 scopes that would be required by the path operations that use this dependency.

TYPE: Optional[Dict[str, str]] DEFAULT: None

description

Security scheme description.

It will be included in the generated OpenAPI (e.g. visible at /docs).

TYPE: Optional[str] DEFAULT: None

auto_error

By default, if no HTTP Auhtorization header is provided, required for OAuth2 authentication, it will automatically cancel the request and send the client an error.

If auto_error is set to False, when the HTTP Authorization header is not available, instead of erroring out, the dependency result will be None.

This is useful when you want to have optional authentication.

It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, with OAuth2 or in a cookie).

TYPE: bool DEFAULT: True

Source code in fastapi/security/oauth2.py

  1. 494
  2. 495
  3. 496
  4. 497
  5. 498
  6. 499
  7. 500
  8. 501
  9. 502
  10. 503
  11. 504
  12. 505
  13. 506
  14. 507
  15. 508
  16. 509
  17. 510
  18. 511
  19. 512
  20. 513
  21. 514
  22. 515
  23. 516
  24. 517
  25. 518
  26. 519
  27. 520
  28. 521
  29. 522
  30. 523
  31. 524
  32. 525
  33. 526
  34. 527
  35. 528
  36. 529
  37. 530
  38. 531
  39. 532
  40. 533
  41. 534
  42. 535
  43. 536
  44. 537
  45. 538
  46. 539
  47. 540
  48. 541
  49. 542
  50. 543
  51. 544
  52. 545
  53. 546
  54. 547
  55. 548
  56. 549
  57. 550
  58. 551
  59. 552
  60. 553
  61. 554
  62. 555
  63. 556
  64. 557
  65. 558
  66. 559
  67. 560
  68. 561
  69. 562
  70. 563
  71. 564
  72. 565
  73. 566
  74. 567
  75. 568
  76. 569
  77. 570
  78. 571
  79. 572
  80. 573
  81. 574
  82. 575
  83. 576
  84. 577
  85. 578
  86. 579
  87. 580
  88. 581
  1. def init(
  2. self,
  3. authorizationUrl: str,
  4. tokenUrl: Annotated[
  5. str,
  6. Doc(
  7. “””
  8. The URL to obtain the OAuth2 token.
  9. “””
  10. ),
  11. ],
  12. refreshUrl: Annotated[
  13. Optional[str],
  14. Doc(
  15. “””
  16. The URL to refresh the token and obtain a new one.
  17. “””
  18. ),
  19. ] = None,
  20. schemename: Annotated[
  21. Optional[str],
  22. Doc(
  23. “””
  24. Security scheme name.
  25. It will be included in the generated OpenAPI (e.g. visible at /docs).
  26. “””
  27. ),
  28. ] = None,
  29. scopes: Annotated[
  30. Optional[Dict[str, str]],
  31. Doc(
  32. “””
  33. The OAuth2 scopes that would be required by the path operations that
  34. use this dependency.
  35. “””
  36. ),
  37. ] = None,
  38. description: Annotated[
  39. Optional[str],
  40. Doc(
  41. “””
  42. Security scheme description.
  43. It will be included in the generated OpenAPI (e.g. visible at /docs).
  44. “””
  45. ),
  46. ] = None,
  47. autoerror: Annotated[
  48. bool,
  49. Doc(
  50. “””
  51. By default, if no HTTP Auhtorization header is provided, required for
  52. OAuth2 authentication, it will automatically cancel the request and
  53. send the client an error.
  54. If auto_error is set to False, when the HTTP Authorization header
  55. is not available, instead of erroring out, the dependency result will
  56. be None.
  57. This is useful when you want to have optional authentication.
  58. It is also useful when you want to have authentication that can be
  59. provided in one of multiple optional ways (for example, with OAuth2
  60. or in a cookie).
  61. “””
  62. ),
  63. ] = True,
  64. ):
  65. if not scopes:
  66. scopes = {}
  67. flows = OAuthFlowsModel(
  68. authorizationCode=cast(
  69. Any,
  70. {
  71. authorizationUrl: authorizationUrl,
  72. tokenUrl: tokenUrl,
  73. refreshUrl: refreshUrl,
  74. scopes: scopes,
  75. },
  76. )
  77. )
  78. super().__init(
  79. flows=flows,
  80. scheme_name=scheme_name,
  81. description=description,
  82. auto_error=auto_error,
  83. )

model instance-attribute

  1. model = OAuth2(
  2. flows=cast(OAuthFlows, flows), description=description
  3. )

scheme_name instance-attribute

  1. scheme_name = scheme_name or __name__

auto_error instance-attribute

  1. auto_error = auto_error

fastapi.security.OAuth2PasswordBearer

  1. OAuth2PasswordBearer(
  2. tokenUrl,
  3. scheme_name=None,
  4. scopes=None,
  5. description=None,
  6. auto_error=True,
  7. )

Bases: [OAuth2](#fastapi.security.OAuth2 "fastapi.security.oauth2.OAuth2")

OAuth2 flow for authentication using a bearer token obtained with a password. An instance of it would be used as a dependency.

Read more about it in the FastAPI docs for Simple OAuth2 with Password and Bearer.

PARAMETERDESCRIPTION
tokenUrl

The URL to obtain the OAuth2 token. This would be the path operation that has OAuth2PasswordRequestForm as a dependency.

TYPE: str

scheme_name

Security scheme name.

It will be included in the generated OpenAPI (e.g. visible at /docs).

TYPE: Optional[str] DEFAULT: None

scopes

The OAuth2 scopes that would be required by the path operations that use this dependency.

TYPE: Optional[Dict[str, str]] DEFAULT: None

description

Security scheme description.

It will be included in the generated OpenAPI (e.g. visible at /docs).

TYPE: Optional[str] DEFAULT: None

auto_error

By default, if no HTTP Auhtorization header is provided, required for OAuth2 authentication, it will automatically cancel the request and send the client an error.

If auto_error is set to False, when the HTTP Authorization header is not available, instead of erroring out, the dependency result will be None.

This is useful when you want to have optional authentication.

It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, with OAuth2 or in a cookie).

TYPE: bool DEFAULT: True

Source code in fastapi/security/oauth2.py

  1. 400
  2. 401
  3. 402
  4. 403
  5. 404
  6. 405
  7. 406
  8. 407
  9. 408
  10. 409
  11. 410
  12. 411
  13. 412
  14. 413
  15. 414
  16. 415
  17. 416
  18. 417
  19. 418
  20. 419
  21. 420
  22. 421
  23. 422
  24. 423
  25. 424
  26. 425
  27. 426
  28. 427
  29. 428
  30. 429
  31. 430
  32. 431
  33. 432
  34. 433
  35. 434
  36. 435
  37. 436
  38. 437
  39. 438
  40. 439
  41. 440
  42. 441
  43. 442
  44. 443
  45. 444
  46. 445
  47. 446
  48. 447
  49. 448
  50. 449
  51. 450
  52. 451
  53. 452
  54. 453
  55. 454
  56. 455
  57. 456
  58. 457
  59. 458
  60. 459
  61. 460
  62. 461
  63. 462
  64. 463
  65. 464
  66. 465
  67. 466
  68. 467
  69. 468
  70. 469
  71. 470
  72. 471
  1. def init(
  2. self,
  3. tokenUrl: Annotated[
  4. str,
  5. Doc(
  6. “””
  7. The URL to obtain the OAuth2 token. This would be the path operation
  8. that has OAuth2PasswordRequestForm as a dependency.
  9. “””
  10. ),
  11. ],
  12. schemename: Annotated[
  13. Optional[str],
  14. Doc(
  15. “””
  16. Security scheme name.
  17. It will be included in the generated OpenAPI (e.g. visible at /docs).
  18. “””
  19. ),
  20. ] = None,
  21. scopes: Annotated[
  22. Optional[Dict[str, str]],
  23. Doc(
  24. “””
  25. The OAuth2 scopes that would be required by the path operations that
  26. use this dependency.
  27. “””
  28. ),
  29. ] = None,
  30. description: Annotated[
  31. Optional[str],
  32. Doc(
  33. “””
  34. Security scheme description.
  35. It will be included in the generated OpenAPI (e.g. visible at /docs).
  36. “””
  37. ),
  38. ] = None,
  39. autoerror: Annotated[
  40. bool,
  41. Doc(
  42. “””
  43. By default, if no HTTP Auhtorization header is provided, required for
  44. OAuth2 authentication, it will automatically cancel the request and
  45. send the client an error.
  46. If auto_error is set to False, when the HTTP Authorization header
  47. is not available, instead of erroring out, the dependency result will
  48. be None.
  49. This is useful when you want to have optional authentication.
  50. It is also useful when you want to have authentication that can be
  51. provided in one of multiple optional ways (for example, with OAuth2
  52. or in a cookie).
  53. “””
  54. ),
  55. ] = True,
  56. ):
  57. if not scopes:
  58. scopes = {}
  59. flows = OAuthFlowsModel(
  60. password=cast(Any, {tokenUrl: tokenUrl, scopes: scopes})
  61. )
  62. super().__init(
  63. flows=flows,
  64. scheme_name=scheme_name,
  65. description=description,
  66. auto_error=auto_error,
  67. )

model instance-attribute

  1. model = OAuth2(
  2. flows=cast(OAuthFlows, flows), description=description
  3. )

scheme_name instance-attribute

  1. scheme_name = scheme_name or __name__

auto_error instance-attribute

  1. auto_error = auto_error

OAuth2 Password Form

fastapi.security.OAuth2PasswordRequestForm

  1. OAuth2PasswordRequestForm(
  2. *,
  3. grant_type=None,
  4. username,
  5. password,
  6. scope="",
  7. client_id=None,
  8. client_secret=None
  9. )

This is a dependency class to collect the username and password as form data for an OAuth2 password flow.

The OAuth2 specification dictates that for a password flow the data should be collected using form data (instead of JSON) and that it should have the specific fields username and password.

All the initialization parameters are extracted from the request.

Read more about it in the FastAPI docs for Simple OAuth2 with Password and Bearer.

Example

  1. from typing import Annotated
  2. from fastapi import Depends, FastAPI
  3. from fastapi.security import OAuth2PasswordRequestForm
  4. app = FastAPI()
  5. @app.post("/login")
  6. def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):
  7. data = {}
  8. data["scopes"] = []
  9. for scope in form_data.scopes:
  10. data["scopes"].append(scope)
  11. if form_data.client_id:
  12. data["client_id"] = form_data.client_id
  13. if form_data.client_secret:
  14. data["client_secret"] = form_data.client_secret
  15. return data

Note that for OAuth2 the scope items:read is a single scope in an opaque string. You could have custom internal logic to separate it by colon caracters (:) or similar, and get the two parts items and read. Many applications do that to group and organize permisions, you could do it as well in your application, just know that that it is application specific, it’s not part of the specification.

PARAMETERDESCRIPTION
grant_type

The OAuth2 spec says it is required and MUST be the fixed string “password”. Nevertheless, this dependency class is permissive and allows not passing it. If you want to enforce it, use instead the OAuth2PasswordRequestFormStrict dependency.

TYPE: Union[str, None] DEFAULT: None

username

username string. The OAuth2 spec requires the exact field name username.

TYPE: str

password

password string. The OAuth2 spec requires the exact field name `password”.

TYPE: str

scope

A single string with actually several scopes separated by spaces. Each scope is also a string.

For example, a single string with:

```python “items:read items:write users:read profile openid” ````

would represent the scopes:

  • items:read
  • items:write
  • users:read
  • profile
  • openid

TYPE: str DEFAULT: ‘’

client_id

If there’s a client_id, it can be sent as part of the form fields. But the OAuth2 specification recommends sending the client_id and client_secret (if any) using HTTP Basic auth.

TYPE: Union[str, None] DEFAULT: None

client_secret

If there’s a client_password (and a client_id), they can be sent as part of the form fields. But the OAuth2 specification recommends sending the client_id and client_secret (if any) using HTTP Basic auth.

TYPE: Union[str, None] DEFAULT: None

Source code in fastapi/security/oauth2.py

  1. 61
  2. 62
  3. 63
  4. 64
  5. 65
  6. 66
  7. 67
  8. 68
  9. 69
  10. 70
  11. 71
  12. 72
  13. 73
  14. 74
  15. 75
  16. 76
  17. 77
  18. 78
  19. 79
  20. 80
  21. 81
  22. 82
  23. 83
  24. 84
  25. 85
  26. 86
  27. 87
  28. 88
  29. 89
  30. 90
  31. 91
  32. 92
  33. 93
  34. 94
  35. 95
  36. 96
  37. 97
  38. 98
  39. 99
  40. 100
  41. 101
  42. 102
  43. 103
  44. 104
  45. 105
  46. 106
  47. 107
  48. 108
  49. 109
  50. 110
  51. 111
  52. 112
  53. 113
  54. 114
  55. 115
  56. 116
  57. 117
  58. 118
  59. 119
  60. 120
  61. 121
  62. 122
  63. 123
  64. 124
  65. 125
  66. 126
  67. 127
  68. 128
  69. 129
  70. 130
  71. 131
  72. 132
  73. 133
  74. 134
  75. 135
  76. 136
  77. 137
  78. 138
  79. 139
  80. 140
  81. 141
  82. 142
  83. 143
  84. 144
  85. 145
  86. 146
  87. 147
  88. 148
  89. 149
  1. def init(
  2. self,
  3. ,
  4. grant_type: Annotated[
  5. Union[str, None],
  6. Form(pattern=password),
  7. Doc(
  8. “””
  9. The OAuth2 spec says it is required and MUST be the fixed string
  10. password”. Nevertheless, this dependency class is permissive and
  11. allows not passing it. If you want to enforce it, use instead the
  12. OAuth2PasswordRequestFormStrict dependency.
  13. “””
  14. ),
  15. ] = None,
  16. username: Annotated[
  17. str,
  18. Form(),
  19. Doc(
  20. “””
  21. username string. The OAuth2 spec requires the exact field name
  22. username.
  23. “””
  24. ),
  25. ],
  26. password: Annotated[
  27. str,
  28. Form(),
  29. Doc(
  30. “””
  31. password string. The OAuth2 spec requires the exact field name
  32. `password”.
  33. “””
  34. ),
  35. ],
  36. scope: Annotated[
  37. str,
  38. Form(),
  39. Doc(
  40. “””
  41. A single string with actually several scopes separated by spaces. Each
  42. scope is also a string.
  43. For example, a single string with:
  44. ```python
  45. items:read items:write users:read profile openid
  46. ````
  47. would represent the scopes:
  48. items:read
  49. items:write
  50. users:read
  51. profile
  52. openid
  53. “””
  54. ),
  55. ] = “”,
  56. client_id: Annotated[
  57. Union[str, None],
  58. Form(),
  59. Doc(
  60. “””
  61. If theres a client_id, it can be sent as part of the form fields.
  62. But the OAuth2 specification recommends sending the client_id and
  63. client_secret (if any) using HTTP Basic auth.
  64. “””
  65. ),
  66. ] = None,
  67. client_secret: Annotated[
  68. Union[str, None],
  69. Form(),
  70. Doc(
  71. “””
  72. If theres a client_password (and a client_id), they can be sent
  73. as part of the form fields. But the OAuth2 specification recommends
  74. sending the client_id and client_secret (if any) using HTTP Basic
  75. auth.
  76. “””
  77. ),
  78. ] = None,
  79. ):
  80. self.grant_type = grant_type
  81. self.username = username
  82. self.password = password
  83. self.scopes = scope.split()
  84. self.client_id = client_id
  85. self.client_secret = client_secret

grant_type instance-attribute

  1. grant_type = grant_type

username instance-attribute

  1. username = username

password instance-attribute

  1. password = password

scopes instance-attribute

  1. scopes = split()

client_id instance-attribute

  1. client_id = client_id

client_secret instance-attribute

  1. client_secret = client_secret

fastapi.security.OAuth2PasswordRequestFormStrict

  1. OAuth2PasswordRequestFormStrict(
  2. grant_type,
  3. username,
  4. password,
  5. scope="",
  6. client_id=None,
  7. client_secret=None,
  8. )

Bases: [OAuth2PasswordRequestForm](#fastapi.security.OAuth2PasswordRequestForm "fastapi.security.oauth2.OAuth2PasswordRequestForm")

This is a dependency class to collect the username and password as form data for an OAuth2 password flow.

The OAuth2 specification dictates that for a password flow the data should be collected using form data (instead of JSON) and that it should have the specific fields username and password.

All the initialization parameters are extracted from the request.

The only difference between OAuth2PasswordRequestFormStrict and OAuth2PasswordRequestForm is that OAuth2PasswordRequestFormStrict requires the client to send the form field grant_type with the value "password", which is required in the OAuth2 specification (it seems that for no particular reason), while for OAuth2PasswordRequestForm grant_type is optional.

Read more about it in the FastAPI docs for Simple OAuth2 with Password and Bearer.

Example

  1. from typing import Annotated
  2. from fastapi import Depends, FastAPI
  3. from fastapi.security import OAuth2PasswordRequestForm
  4. app = FastAPI()
  5. @app.post("/login")
  6. def login(form_data: Annotated[OAuth2PasswordRequestFormStrict, Depends()]):
  7. data = {}
  8. data["scopes"] = []
  9. for scope in form_data.scopes:
  10. data["scopes"].append(scope)
  11. if form_data.client_id:
  12. data["client_id"] = form_data.client_id
  13. if form_data.client_secret:
  14. data["client_secret"] = form_data.client_secret
  15. return data

Note that for OAuth2 the scope items:read is a single scope in an opaque string. You could have custom internal logic to separate it by colon caracters (:) or similar, and get the two parts items and read. Many applications do that to group and organize permisions, you could do it as well in your application, just know that that it is application specific, it’s not part of the specification.

the OAuth2 spec says it is required and MUST be the fixed string “password”.

This dependency is strict about it. If you want to be permissive, use instead the OAuth2PasswordRequestForm dependency class.

username: username string. The OAuth2 spec requires the exact field name “username”. password: password string. The OAuth2 spec requires the exact field name “password”. scope: Optional string. Several scopes (each one a string) separated by spaces. E.g. “items:read items:write users:read profile openid” client_id: optional string. OAuth2 recommends sending the client_id and client_secret (if any) using HTTP Basic auth, as: client_id:client_secret client_secret: optional string. OAuth2 recommends sending the client_id and client_secret (if any) using HTTP Basic auth, as: client_id:client_secret

PARAMETERDESCRIPTION
grant_type

The OAuth2 spec says it is required and MUST be the fixed string “password”. This dependency is strict about it. If you want to be permissive, use instead the OAuth2PasswordRequestForm dependency class.

TYPE: str

username

username string. The OAuth2 spec requires the exact field name username.

TYPE: str

password

password string. The OAuth2 spec requires the exact field name `password”.

TYPE: str

scope

A single string with actually several scopes separated by spaces. Each scope is also a string.

For example, a single string with:

```python “items:read items:write users:read profile openid” ````

would represent the scopes:

  • items:read
  • items:write
  • users:read
  • profile
  • openid

TYPE: str DEFAULT: ‘’

client_id

If there’s a client_id, it can be sent as part of the form fields. But the OAuth2 specification recommends sending the client_id and client_secret (if any) using HTTP Basic auth.

TYPE: Union[str, None] DEFAULT: None

client_secret

If there’s a client_password (and a client_id), they can be sent as part of the form fields. But the OAuth2 specification recommends sending the client_id and client_secret (if any) using HTTP Basic auth.

TYPE: Union[str, None] DEFAULT: None

Source code in fastapi/security/oauth2.py

  1. 216
  2. 217
  3. 218
  4. 219
  5. 220
  6. 221
  7. 222
  8. 223
  9. 224
  10. 225
  11. 226
  12. 227
  13. 228
  14. 229
  15. 230
  16. 231
  17. 232
  18. 233
  19. 234
  20. 235
  21. 236
  22. 237
  23. 238
  24. 239
  25. 240
  26. 241
  27. 242
  28. 243
  29. 244
  30. 245
  31. 246
  32. 247
  33. 248
  34. 249
  35. 250
  36. 251
  37. 252
  38. 253
  39. 254
  40. 255
  41. 256
  42. 257
  43. 258
  44. 259
  45. 260
  46. 261
  47. 262
  48. 263
  49. 264
  50. 265
  51. 266
  52. 267
  53. 268
  54. 269
  55. 270
  56. 271
  57. 272
  58. 273
  59. 274
  60. 275
  61. 276
  62. 277
  63. 278
  64. 279
  65. 280
  66. 281
  67. 282
  68. 283
  69. 284
  70. 285
  71. 286
  72. 287
  73. 288
  74. 289
  75. 290
  76. 291
  77. 292
  78. 293
  79. 294
  80. 295
  81. 296
  82. 297
  83. 298
  84. 299
  85. 300
  86. 301
  87. 302
  88. 303
  89. 304
  90. 305
  1. def init(
  2. self,
  3. granttype: Annotated[
  4. str,
  5. Form(pattern=password),
  6. Doc(
  7. “””
  8. The OAuth2 spec says it is required and MUST be the fixed string
  9. password”. This dependency is strict about it. If you want to be
  10. permissive, use instead the OAuth2PasswordRequestForm dependency
  11. class.
  12. “””
  13. ),
  14. ],
  15. username: Annotated[
  16. str,
  17. Form(),
  18. Doc(
  19. “””
  20. username string. The OAuth2 spec requires the exact field name
  21. username.
  22. “””
  23. ),
  24. ],
  25. password: Annotated[
  26. str,
  27. Form(),
  28. Doc(
  29. “””
  30. password string. The OAuth2 spec requires the exact field name
  31. password".</span>
  32. <span> """</span>
  33. <span>),</span>
  34. <span>],</span>
  35. <span>scope</span><span>:</span> <span>Annotated</span><span>[</span>
  36. <span>str</span><span>,</span>
  37. <span>Form</span><span>(),</span>
  38. <span>Doc</span><span>(</span>
  39. <span> </span><span>"""</span>
  40. <span> A single string with actually several scopes separated by spaces. Each</span>
  41. <span> scope is also a string.</span>
  42. <span> For example, a single string with:</span>
  43. <span> ```python</span>
  44. <span> "items:read items:write users:read profile openid"</span>
  45. <span> ````</span>
  46. <span> would represent the scopes:</span>
  47. <span> *items:read</span>
  48. <span> *items:write</span>
  49. <span> *users:read</span>
  50. <span> *profile</span>
  51. <span> *openid</span>
  52. <span> """</span>
  53. <span>),</span>
  54. <span>]</span> <span>=</span> <span>""</span><span>,</span>
  55. <span>client_id</span><span>:</span> <span>Annotated</span><span>[</span>
  56. <span>Union</span><span>[</span><span>str</span><span>,</span> <span>None</span><span>],</span>
  57. <span>Form</span><span>(),</span>
  58. <span>Doc</span><span>(</span>
  59. <span> </span><span>"""</span>
  60. <span> If there's aclientid, it can be sent as part of the form fields.</span>
  61. <span> But the OAuth2 specification recommends sending theclient_idand</span>
  62. <span>client_secret(if any) using HTTP Basic auth.</span>
  63. <span> """</span>
  64. <span>),</span>
  65. <span>]</span> <span>=</span> <span>None</span><span>,</span>
  66. <span>client_secret</span><span>:</span> <span>Annotated</span><span>[</span>
  67. <span>Union</span><span>[</span><span>str</span><span>,</span> <span>None</span><span>],</span>
  68. <span>Form</span><span>(),</span>
  69. <span>Doc</span><span>(</span>
  70. <span> </span><span>"""</span>
  71. <span> If there's aclient_password(and aclient_id), they can be sent</span>
  72. <span> as part of the form fields. But the OAuth2 specification recommends</span>
  73. <span> sending theclient_idandclient_secret` (if any) using HTTP Basic
  74. auth.
  75. “””
  76. ),
  77. ] = None,
  78. ):
  79. super().__init(
  80. grant_type=grant_type,
  81. username=username,
  82. password=password,
  83. scope=scope,
  84. client_id=client_id,
  85. client_secret=client_secret,
  86. )

grant_type instance-attribute

  1. grant_type = grant_type

username instance-attribute

  1. username = username

password instance-attribute

  1. password = password

scopes instance-attribute

  1. scopes = split()

client_id instance-attribute

  1. client_id = client_id

client_secret instance-attribute

  1. client_secret = client_secret

OAuth2 Security Scopes in Dependencies

fastapi.security.SecurityScopes

  1. SecurityScopes(scopes=None)

This is a special class that you can define in a parameter in a dependency to obtain the OAuth2 scopes required by all the dependencies in the same chain.

This way, multiple dependencies can have different scopes, even when used in the same path operation. And with this, you can access all the scopes required in all those dependencies in a single place.

Read more about it in the FastAPI docs for OAuth2 scopes.

PARAMETERDESCRIPTION
scopes

This will be filled by FastAPI.

TYPE: Optional[List[str]] DEFAULT: None

Source code in fastapi/security/oauth2.py

  1. 611
  2. 612
  3. 613
  4. 614
  5. 615
  6. 616
  7. 617
  8. 618
  9. 619
  10. 620
  11. 621
  12. 622
  13. 623
  14. 624
  15. 625
  16. 626
  17. 627
  18. 628
  19. 629
  20. 630
  21. 631
  22. 632
  23. 633
  24. 634
  25. 635
  26. 636
  27. 637
  28. 638
  29. 639
  30. 640
  1. def init(
  2. self,
  3. scopes: Annotated[
  4. Optional[List[str]],
  5. Doc(
  6. “””
  7. This will be filled by FastAPI.
  8. “””
  9. ),
  10. ] = None,
  11. ):
  12. self.scopes: Annotated[
  13. List[str],
  14. Doc(
  15. “””
  16. The list of all the scopes required by dependencies.
  17. “””
  18. ),
  19. ] = (
  20. scopes or []
  21. )
  22. self.scope_str: Annotated[
  23. str,
  24. Doc(
  25. “””
  26. All the scopes required by all the dependencies in a single string
  27. separated by spaces, as defined in the OAuth2 specification.
  28. “””
  29. ),
  30. ] = .join(self.scopes)

scopes instance-attribute

  1. scopes = scopes or []

The list of all the scopes required by dependencies.

scope_str instance-attribute

  1. scope_str = join(scopes)

All the scopes required by all the dependencies in a single string separated by spaces, as defined in the OAuth2 specification.

OpenID Connect

fastapi.security.OpenIdConnect

  1. OpenIdConnect(
  2. *,
  3. openIdConnectUrl,
  4. scheme_name=None,
  5. description=None,
  6. auto_error=True
  7. )

Bases: SecurityBase

OpenID Connect authentication class. An instance of it would be used as a dependency.

PARAMETERDESCRIPTION
openIdConnectUrl

The OpenID Connect URL.

TYPE: str

scheme_name

Security scheme name.

It will be included in the generated OpenAPI (e.g. visible at /docs).

TYPE: Optional[str] DEFAULT: None

description

Security scheme description.

It will be included in the generated OpenAPI (e.g. visible at /docs).

TYPE: Optional[str] DEFAULT: None

auto_error

By default, if no HTTP Auhtorization header is provided, required for OpenID Connect authentication, it will automatically cancel the request and send the client an error.

If auto_error is set to False, when the HTTP Authorization header is not available, instead of erroring out, the dependency result will be None.

This is useful when you want to have optional authentication.

It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, with OpenID Connect or in a cookie).

TYPE: bool DEFAULT: True

Source code in fastapi/security/open_id_connect_url.py

  1. 17
  2. 18
  3. 19
  4. 20
  5. 21
  6. 22
  7. 23
  8. 24
  9. 25
  10. 26
  11. 27
  12. 28
  13. 29
  14. 30
  15. 31
  16. 32
  17. 33
  18. 34
  19. 35
  20. 36
  21. 37
  22. 38
  23. 39
  24. 40
  25. 41
  26. 42
  27. 43
  28. 44
  29. 45
  30. 46
  31. 47
  32. 48
  33. 49
  34. 50
  35. 51
  36. 52
  37. 53
  38. 54
  39. 55
  40. 56
  41. 57
  42. 58
  43. 59
  44. 60
  45. 61
  46. 62
  47. 63
  48. 64
  49. 65
  50. 66
  51. 67
  52. 68
  53. 69
  54. 70
  55. 71
  56. 72
  57. 73
  1. def init(
  2. self,
  3. *,
  4. openIdConnectUrl: Annotated[
  5. str,
  6. Doc(
  7. “””
  8. The OpenID Connect URL.
  9. “””
  10. ),
  11. ],
  12. schemename: Annotated[
  13. Optional[str],
  14. Doc(
  15. “””
  16. Security scheme name.
  17. It will be included in the generated OpenAPI (e.g. visible at /docs).
  18. “””
  19. ),
  20. ] = None,
  21. description: Annotated[
  22. Optional[str],
  23. Doc(
  24. “””
  25. Security scheme description.
  26. It will be included in the generated OpenAPI (e.g. visible at /docs).
  27. “””
  28. ),
  29. ] = None,
  30. autoerror: Annotated[
  31. bool,
  32. Doc(
  33. “””
  34. By default, if no HTTP Auhtorization header is provided, required for
  35. OpenID Connect authentication, it will automatically cancel the request
  36. and send the client an error.
  37. If auto_error is set to False, when the HTTP Authorization header
  38. is not available, instead of erroring out, the dependency result will
  39. be None.
  40. This is useful when you want to have optional authentication.
  41. It is also useful when you want to have authentication that can be
  42. provided in one of multiple optional ways (for example, with OpenID
  43. Connect or in a cookie).
  44. “””
  45. ),
  46. ] = True,
  47. ):
  48. self.model = OpenIdConnectModel(
  49. openIdConnectUrl=openIdConnectUrl, description=description
  50. )
  51. self.schemename = schemename or self.__class.__name
  52. self.auto_error = auto_error

model instance-attribute

  1. model = OpenIdConnect(
  2. openIdConnectUrl=openIdConnectUrl,
  3. description=description,
  4. )

scheme_name instance-attribute

  1. scheme_name = scheme_name or __name__

auto_error instance-attribute

  1. auto_error = auto_error