跳到内容

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

from fastapi.security import (
    APIKeyCookie,
    APIKeyHeader,
    APIKeyQuery,
    HTTPAuthorizationCredentials,
    HTTPBasic,
    HTTPBasicCredentials,
    HTTPBearer,
    HTTPDigest,
    OAuth2,
    OAuth2AuthorizationCodeBearer,
    OAuth2PasswordBearer,
    OAuth2PasswordRequestForm,
    OAuth2PasswordRequestFormStrict,
    OpenIdConnect,
    SecurityScopes,
)

API Key Security Schemes

fastapi.security.APIKeyCookie

APIKeyCookie(
    *,
    name,
    scheme_name=None,
    description=None,
    auto_error=True
)

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

from fastapi import Depends, FastAPI
from fastapi.security import APIKeyCookie

app = FastAPI()

cookie_scheme = APIKeyCookie(name="session")


@app.get("/items/")
async def read_items(session: str = Depends(cookie_scheme)):
    return {"session": session}
参数 描述
name

Cookie name.

类型: str

scheme_name

Security scheme name.

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

类型: Optional[str] 默认值: None

description

Security scheme description.

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

类型: Optional[str] 默认值: 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).

类型: bool 默认值: True

Source code in fastapi/security/api_key.py
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
def __init__(
    self,
    *,
    name: Annotated[str, Doc("Cookie name.")],
    scheme_name: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme name.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme description.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            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).
            """
        ),
    ] = True,
):
    super().__init__(
        location=APIKeyIn.cookie,
        name=name,
        scheme_name=scheme_name,
        description=description,
        auto_error=auto_error,
    )

model instance-attribute

model = APIKey(
    **{"in": location}, name=name, description=description
)

scheme_name instance-attribute

scheme_name = scheme_name or __name__

auto_error instance-attribute

auto_error = auto_error

make_not_authenticated_error

make_not_authenticated_error()

The WWW-Authenticate header is not standardized for API Key authentication but the HTTP specification requires that an error of 401 "Unauthorized" must include a WWW-Authenticate header.

Ref: https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized

For this, this method sends a custom challenge APIKey.

Source code in fastapi/security/api_key.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def make_not_authenticated_error(self) -> HTTPException:
    """
    The WWW-Authenticate header is not standardized for API Key authentication but
    the HTTP specification requires that an error of 401 "Unauthorized" must
    include a WWW-Authenticate header.

    Ref: https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized

    For this, this method sends a custom challenge `APIKey`.
    """
    return HTTPException(
        status_code=HTTP_401_UNAUTHORIZED,
        detail="Not authenticated",
        headers={"WWW-Authenticate": "APIKey"},
    )

check_api_key

check_api_key(api_key)
Source code in fastapi/security/api_key.py
45
46
47
48
49
50
def check_api_key(self, api_key: Optional[str]) -> Optional[str]:
    if not api_key:
        if self.auto_error:
            raise self.make_not_authenticated_error()
        return None
    return api_key

fastapi.security.APIKeyHeader

APIKeyHeader(
    *,
    name,
    scheme_name=None,
    description=None,
    auto_error=True
)

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

from fastapi import Depends, FastAPI
from fastapi.security import APIKeyHeader

app = FastAPI()

header_scheme = APIKeyHeader(name="x-key")


@app.get("/items/")
async def read_items(key: str = Depends(header_scheme)):
    return {"key": key}
参数 描述
name

Header name.

类型: str

scheme_name

Security scheme name.

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

类型: Optional[str] 默认值: None

description

Security scheme description.

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

类型: Optional[str] 默认值: 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).

类型: bool 默认值: True

Source code in fastapi/security/api_key.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
def __init__(
    self,
    *,
    name: Annotated[str, Doc("Header name.")],
    scheme_name: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme name.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme description.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            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).
            """
        ),
    ] = True,
):
    super().__init__(
        location=APIKeyIn.header,
        name=name,
        scheme_name=scheme_name,
        description=description,
        auto_error=auto_error,
    )

model instance-attribute

model = APIKey(
    **{"in": location}, name=name, description=description
)

scheme_name instance-attribute

scheme_name = scheme_name or __name__

auto_error instance-attribute

auto_error = auto_error

make_not_authenticated_error

make_not_authenticated_error()

The WWW-Authenticate header is not standardized for API Key authentication but the HTTP specification requires that an error of 401 "Unauthorized" must include a WWW-Authenticate header.

Ref: https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized

For this, this method sends a custom challenge APIKey.

Source code in fastapi/security/api_key.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def make_not_authenticated_error(self) -> HTTPException:
    """
    The WWW-Authenticate header is not standardized for API Key authentication but
    the HTTP specification requires that an error of 401 "Unauthorized" must
    include a WWW-Authenticate header.

    Ref: https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized

    For this, this method sends a custom challenge `APIKey`.
    """
    return HTTPException(
        status_code=HTTP_401_UNAUTHORIZED,
        detail="Not authenticated",
        headers={"WWW-Authenticate": "APIKey"},
    )

check_api_key

check_api_key(api_key)
Source code in fastapi/security/api_key.py
45
46
47
48
49
50
def check_api_key(self, api_key: Optional[str]) -> Optional[str]:
    if not api_key:
        if self.auto_error:
            raise self.make_not_authenticated_error()
        return None
    return api_key

fastapi.security.APIKeyQuery

APIKeyQuery(
    *,
    name,
    scheme_name=None,
    description=None,
    auto_error=True
)

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

from fastapi import Depends, FastAPI
from fastapi.security import APIKeyQuery

app = FastAPI()

query_scheme = APIKeyQuery(name="api_key")


@app.get("/items/")
async def read_items(api_key: str = Depends(query_scheme)):
    return {"api_key": api_key}
参数 描述
name

Query parameter name.

类型: str

scheme_name

Security scheme name.

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

类型: Optional[str] 默认值: None

description

Security scheme description.

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

类型: Optional[str] 默认值: None

auto_error

By default, if the query parameter is not provided, APIKeyQuery will automatically cancel the request and send 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).

类型: bool 默认值: True

Source code in fastapi/security/api_key.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def __init__(
    self,
    *,
    name: Annotated[
        str,
        Doc("Query parameter name."),
    ],
    scheme_name: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme name.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme description.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if the query parameter is not provided, `APIKeyQuery` will
            automatically cancel the request and send 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).
            """
        ),
    ] = True,
):
    super().__init__(
        location=APIKeyIn.query,
        name=name,
        scheme_name=scheme_name,
        description=description,
        auto_error=auto_error,
    )

model instance-attribute

model = APIKey(
    **{"in": location}, name=name, description=description
)

scheme_name instance-attribute

scheme_name = scheme_name or __name__

auto_error instance-attribute

auto_error = auto_error

make_not_authenticated_error

make_not_authenticated_error()

The WWW-Authenticate header is not standardized for API Key authentication but the HTTP specification requires that an error of 401 "Unauthorized" must include a WWW-Authenticate header.

Ref: https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized

For this, this method sends a custom challenge APIKey.

Source code in fastapi/security/api_key.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def make_not_authenticated_error(self) -> HTTPException:
    """
    The WWW-Authenticate header is not standardized for API Key authentication but
    the HTTP specification requires that an error of 401 "Unauthorized" must
    include a WWW-Authenticate header.

    Ref: https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized

    For this, this method sends a custom challenge `APIKey`.
    """
    return HTTPException(
        status_code=HTTP_401_UNAUTHORIZED,
        detail="Not authenticated",
        headers={"WWW-Authenticate": "APIKey"},
    )

check_api_key

check_api_key(api_key)
Source code in fastapi/security/api_key.py
45
46
47
48
49
50
def check_api_key(self, api_key: Optional[str]) -> Optional[str]:
    if not api_key:
        if self.auto_error:
            raise self.make_not_authenticated_error()
        return None
    return api_key

HTTP Authentication Schemes

fastapi.security.HTTPBasic

HTTPBasic(
    *,
    scheme_name=None,
    realm=None,
    description=None,
    auto_error=True
)

Bases: HTTPBase

HTTP Basic authentication.

Ref: https://datatracker.ietf.org/doc/html/rfc7617

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

from typing import Annotated

from fastapi import Depends, FastAPI
from fastapi.security import HTTPBasic, HTTPBasicCredentials

app = FastAPI()

security = HTTPBasic()


@app.get("/users/me")
def read_current_user(credentials: Annotated[HTTPBasicCredentials, Depends(security)]):
    return {"username": credentials.username, "password": credentials.password}
参数 描述
scheme_name

Security scheme name.

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

类型: Optional[str] 默认值: None

realm

HTTP Basic authentication realm.

类型: Optional[str] 默认值: None

description

Security scheme description.

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

类型: Optional[str] 默认值: 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).

类型: bool 默认值: True

Source code in fastapi/security/http.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
def __init__(
    self,
    *,
    scheme_name: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme name.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    realm: Annotated[
        Optional[str],
        Doc(
            """
            HTTP Basic authentication realm.
            """
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme description.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            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).
            """
        ),
    ] = True,
):
    self.model = HTTPBaseModel(scheme="basic", description=description)
    self.scheme_name = scheme_name or self.__class__.__name__
    self.realm = realm
    self.auto_error = auto_error

model instance-attribute

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

scheme_name instance-attribute

scheme_name = scheme_name or __name__

realm instance-attribute

realm = realm

auto_error instance-attribute

auto_error = auto_error

make_not_authenticated_error

make_not_authenticated_error()
Source code in fastapi/security/http.py
87
88
89
90
91
92
def make_not_authenticated_error(self) -> HTTPException:
    return HTTPException(
        status_code=HTTP_401_UNAUTHORIZED,
        detail="Not authenticated",
        headers=self.make_authenticate_headers(),
    )

make_authenticate_headers

make_authenticate_headers()
Source code in fastapi/security/http.py
199
200
201
202
def make_authenticate_headers(self) -> dict[str, str]:
    if self.realm:
        return {"WWW-Authenticate": f'Basic realm="{self.realm}"'}
    return {"WWW-Authenticate": "Basic"}

fastapi.security.HTTPBearer

HTTPBearer(
    *,
    bearerFormat=None,
    scheme_name=None,
    description=None,
    auto_error=True
)

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

from typing import Annotated

from fastapi import Depends, FastAPI
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer

app = FastAPI()

security = HTTPBearer()


@app.get("/users/me")
def read_current_user(
    credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)]
):
    return {"scheme": credentials.scheme, "credentials": credentials.credentials}
参数 描述
bearerFormat

Bearer token format.

类型: Optional[str] 默认值: None

scheme_name

Security scheme name.

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

类型: Optional[str] 默认值: None

description

Security scheme description.

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

类型: Optional[str] 默认值: None

auto_error

By default, if the HTTP Bearer token is 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).

类型: bool 默认值: True

Source code in fastapi/security/http.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
def __init__(
    self,
    *,
    bearerFormat: Annotated[Optional[str], Doc("Bearer token format.")] = None,
    scheme_name: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme name.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme description.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if the HTTP Bearer token is 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).
            """
        ),
    ] = True,
):
    self.model = HTTPBearerModel(bearerFormat=bearerFormat, description=description)
    self.scheme_name = scheme_name or self.__class__.__name__
    self.auto_error = auto_error

model instance-attribute

model = HTTPBearer(
    bearerFormat=bearerFormat, description=description
)

scheme_name instance-attribute

scheme_name = scheme_name or __name__

auto_error instance-attribute

auto_error = auto_error

make_authenticate_headers

make_authenticate_headers()
Source code in fastapi/security/http.py
84
85
def make_authenticate_headers(self) -> dict[str, str]:
    return {"WWW-Authenticate": f"{self.model.scheme.title()}"}

make_not_authenticated_error

make_not_authenticated_error()
Source code in fastapi/security/http.py
87
88
89
90
91
92
def make_not_authenticated_error(self) -> HTTPException:
    return HTTPException(
        status_code=HTTP_401_UNAUTHORIZED,
        detail="Not authenticated",
        headers=self.make_authenticate_headers(),
    )

fastapi.security.HTTPDigest

HTTPDigest(
    *, scheme_name=None, description=None, auto_error=True
)

Bases: HTTPBase

HTTP Digest authentication.

Warning: this is only a stub to connect the components with OpenAPI in FastAPI, but it doesn't implement the full Digest scheme, you would need to to subclass it and implement it in your code.

Ref: https://datatracker.ietf.org/doc/html/rfc7616

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

from typing import Annotated

from fastapi import Depends, FastAPI
from fastapi.security import HTTPAuthorizationCredentials, HTTPDigest

app = FastAPI()

security = HTTPDigest()


@app.get("/users/me")
def read_current_user(
    credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)]
):
    return {"scheme": credentials.scheme, "credentials": credentials.credentials}
参数 描述
scheme_name

Security scheme name.

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

类型: Optional[str] 默认值: None

description

Security scheme description.

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

类型: Optional[str] 默认值: None

auto_error

By default, if the HTTP Digest is 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).

类型: bool 默认值: True

Source code in fastapi/security/http.py
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
def __init__(
    self,
    *,
    scheme_name: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme name.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme description.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if the HTTP Digest is 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).
            """
        ),
    ] = True,
):
    self.model = HTTPBaseModel(scheme="digest", description=description)
    self.scheme_name = scheme_name or self.__class__.__name__
    self.auto_error = auto_error

model instance-attribute

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

scheme_name instance-attribute

scheme_name = scheme_name or __name__

auto_error instance-attribute

auto_error = auto_error

make_authenticate_headers

make_authenticate_headers()
Source code in fastapi/security/http.py
84
85
def make_authenticate_headers(self) -> dict[str, str]:
    return {"WWW-Authenticate": f"{self.model.scheme.title()}"}

make_not_authenticated_error

make_not_authenticated_error()
Source code in fastapi/security/http.py
87
88
89
90
91
92
def make_not_authenticated_error(self) -> HTTPException:
    return HTTPException(
        status_code=HTTP_401_UNAUTHORIZED,
        detail="Not authenticated",
        headers=self.make_authenticate_headers(),
    )

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

Authorization: Bearer deadbeef12346

In this case

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

scheme instance-attribute

scheme

The HTTP authorization scheme extracted from the header value.

credentials instance-attribute

credentials

The HTTP authorization credentials extracted from the header value.

fastapi.security.HTTPBasicCredentials

Bases: BaseModel

The HTTP Basic credentials 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

username

The HTTP Basic username.

password instance-attribute

password

The HTTP Basic password.

OAuth2 Authentication

fastapi.security.OAuth2

OAuth2(
    *,
    flows=OAuthFlows(),
    scheme_name=None,
    description=None,
    auto_error=True
)

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.

参数 描述
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).

类型: Optional[str] 默认值: None

description

Security scheme description.

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

类型: Optional[str] 默认值: None

auto_error

By default, if no HTTP Authorization 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).

类型: bool 默认值: True

Source code in fastapi/security/oauth2.py
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
def __init__(
    self,
    *,
    flows: Annotated[
        Union[OAuthFlowsModel, dict[str, dict[str, Any]]],
        Doc(
            """
            The dictionary of OAuth2 flows.
            """
        ),
    ] = OAuthFlowsModel(),
    scheme_name: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme name.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme description.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if no HTTP Authorization 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).
            """
        ),
    ] = True,
):
    self.model = OAuth2Model(
        flows=cast(OAuthFlowsModel, flows), description=description
    )
    self.scheme_name = scheme_name or self.__class__.__name__
    self.auto_error = auto_error

model instance-attribute

model = OAuth2(
    flows=cast(OAuthFlows, flows), description=description
)

scheme_name instance-attribute

scheme_name = scheme_name or __name__

auto_error instance-attribute

auto_error = auto_error

make_not_authenticated_error

make_not_authenticated_error()

The OAuth 2 specification doesn't define the challenge that should be used, because a Bearer token is not really the only option to authenticate.

But declaring any other authentication challenge would be application-specific as it's not defined in the specification.

For practical reasons, this method uses the Bearer challenge by default, as it's probably the most common one.

If you are implementing an OAuth2 authentication scheme other than the provided ones in FastAPI (based on bearer tokens), you might want to override this.

Ref: https://datatracker.ietf.org/doc/html/rfc6749

Source code in fastapi/security/oauth2.py
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
def make_not_authenticated_error(self) -> HTTPException:
    """
    The OAuth 2 specification doesn't define the challenge that should be used,
    because a `Bearer` token is not really the only option to authenticate.

    But declaring any other authentication challenge would be application-specific
    as it's not defined in the specification.

    For practical reasons, this method uses the `Bearer` challenge by default, as
    it's probably the most common one.

    If you are implementing an OAuth2 authentication scheme other than the provided
    ones in FastAPI (based on bearer tokens), you might want to override this.

    Ref: https://datatracker.ietf.org/doc/html/rfc6749
    """
    return HTTPException(
        status_code=HTTP_401_UNAUTHORIZED,
        detail="Not authenticated",
        headers={"WWW-Authenticate": "Bearer"},
    )

fastapi.security.OAuth2AuthorizationCodeBearer

OAuth2AuthorizationCodeBearer(
    authorizationUrl,
    tokenUrl,
    refreshUrl=None,
    scheme_name=None,
    scopes=None,
    description=None,
    auto_error=True,
)

Bases: 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.

参数 描述
tokenUrl

The URL to obtain the OAuth2 token.

类型: str

refreshUrl

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

类型: Optional[str] 默认值: None

scheme_name

Security scheme name.

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

类型: Optional[str] 默认值: 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).

类型: Optional[str] 默认值: None

auto_error

By default, if no HTTP Authorization 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).

类型: bool 默认值: True

Source code in fastapi/security/oauth2.py
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
def __init__(
    self,
    authorizationUrl: str,
    tokenUrl: Annotated[
        str,
        Doc(
            """
            The URL to obtain the OAuth2 token.
            """
        ),
    ],
    refreshUrl: Annotated[
        Optional[str],
        Doc(
            """
            The URL to refresh the token and obtain a new one.
            """
        ),
    ] = None,
    scheme_name: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme name.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    scopes: Annotated[
        Optional[dict[str, str]],
        Doc(
            """
            The OAuth2 scopes that would be required by the *path operations* that
            use this dependency.
            """
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme description.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if no HTTP Authorization 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).
            """
        ),
    ] = True,
):
    if not scopes:
        scopes = {}
    flows = OAuthFlowsModel(
        authorizationCode=cast(
            Any,
            {
                "authorizationUrl": authorizationUrl,
                "tokenUrl": tokenUrl,
                "refreshUrl": refreshUrl,
                "scopes": scopes,
            },
        )
    )
    super().__init__(
        flows=flows,
        scheme_name=scheme_name,
        description=description,
        auto_error=auto_error,
    )

model instance-attribute

model = OAuth2(
    flows=cast(OAuthFlows, flows), description=description
)

scheme_name instance-attribute

scheme_name = scheme_name or __name__

auto_error instance-attribute

auto_error = auto_error

make_not_authenticated_error

make_not_authenticated_error()

The OAuth 2 specification doesn't define the challenge that should be used, because a Bearer token is not really the only option to authenticate.

But declaring any other authentication challenge would be application-specific as it's not defined in the specification.

For practical reasons, this method uses the Bearer challenge by default, as it's probably the most common one.

If you are implementing an OAuth2 authentication scheme other than the provided ones in FastAPI (based on bearer tokens), you might want to override this.

Ref: https://datatracker.ietf.org/doc/html/rfc6749

Source code in fastapi/security/oauth2.py
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
def make_not_authenticated_error(self) -> HTTPException:
    """
    The OAuth 2 specification doesn't define the challenge that should be used,
    because a `Bearer` token is not really the only option to authenticate.

    But declaring any other authentication challenge would be application-specific
    as it's not defined in the specification.

    For practical reasons, this method uses the `Bearer` challenge by default, as
    it's probably the most common one.

    If you are implementing an OAuth2 authentication scheme other than the provided
    ones in FastAPI (based on bearer tokens), you might want to override this.

    Ref: https://datatracker.ietf.org/doc/html/rfc6749
    """
    return HTTPException(
        status_code=HTTP_401_UNAUTHORIZED,
        detail="Not authenticated",
        headers={"WWW-Authenticate": "Bearer"},
    )

fastapi.security.OAuth2PasswordBearer

OAuth2PasswordBearer(
    tokenUrl,
    scheme_name=None,
    scopes=None,
    description=None,
    auto_error=True,
    refreshUrl=None,
)

Bases: 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.

参数 描述
tokenUrl

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

类型: str

scheme_name

Security scheme name.

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

类型: Optional[str] 默认值: 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).

类型: Optional[str] 默认值: None

auto_error

By default, if no HTTP Authorization 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).

类型: bool 默认值: True

refreshUrl

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

类型: Optional[str] 默认值: None

Source code in fastapi/security/oauth2.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
def __init__(
    self,
    tokenUrl: Annotated[
        str,
        Doc(
            """
            The URL to obtain the OAuth2 token. This would be the *path operation*
            that has `OAuth2PasswordRequestForm` as a dependency.
            """
        ),
    ],
    scheme_name: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme name.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    scopes: Annotated[
        Optional[dict[str, str]],
        Doc(
            """
            The OAuth2 scopes that would be required by the *path operations* that
            use this dependency.
            """
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme description.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if no HTTP Authorization 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).
            """
        ),
    ] = True,
    refreshUrl: Annotated[
        Optional[str],
        Doc(
            """
            The URL to refresh the token and obtain a new one.
            """
        ),
    ] = None,
):
    if not scopes:
        scopes = {}
    flows = OAuthFlowsModel(
        password=cast(
            Any,
            {
                "tokenUrl": tokenUrl,
                "refreshUrl": refreshUrl,
                "scopes": scopes,
            },
        )
    )
    super().__init__(
        flows=flows,
        scheme_name=scheme_name,
        description=description,
        auto_error=auto_error,
    )

model instance-attribute

model = OAuth2(
    flows=cast(OAuthFlows, flows), description=description
)

scheme_name instance-attribute

scheme_name = scheme_name or __name__

auto_error instance-attribute

auto_error = auto_error

make_not_authenticated_error

make_not_authenticated_error()

The OAuth 2 specification doesn't define the challenge that should be used, because a Bearer token is not really the only option to authenticate.

But declaring any other authentication challenge would be application-specific as it's not defined in the specification.

For practical reasons, this method uses the Bearer challenge by default, as it's probably the most common one.

If you are implementing an OAuth2 authentication scheme other than the provided ones in FastAPI (based on bearer tokens), you might want to override this.

Ref: https://datatracker.ietf.org/doc/html/rfc6749

Source code in fastapi/security/oauth2.py
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
def make_not_authenticated_error(self) -> HTTPException:
    """
    The OAuth 2 specification doesn't define the challenge that should be used,
    because a `Bearer` token is not really the only option to authenticate.

    But declaring any other authentication challenge would be application-specific
    as it's not defined in the specification.

    For practical reasons, this method uses the `Bearer` challenge by default, as
    it's probably the most common one.

    If you are implementing an OAuth2 authentication scheme other than the provided
    ones in FastAPI (based on bearer tokens), you might want to override this.

    Ref: https://datatracker.ietf.org/doc/html/rfc6749
    """
    return HTTPException(
        status_code=HTTP_401_UNAUTHORIZED,
        detail="Not authenticated",
        headers={"WWW-Authenticate": "Bearer"},
    )

OAuth2 Password Form

fastapi.security.OAuth2PasswordRequestForm

OAuth2PasswordRequestForm(
    *,
    grant_type=None,
    username,
    password,
    scope="",
    client_id=None,
    client_secret=None
)

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

from typing import Annotated

from fastapi import Depends, FastAPI
from fastapi.security import OAuth2PasswordRequestForm

app = FastAPI()


@app.post("/login")
def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):
    data = {}
    data["scopes"] = []
    for scope in form_data.scopes:
        data["scopes"].append(scope)
    if form_data.client_id:
        data["client_id"] = form_data.client_id
    if form_data.client_secret:
        data["client_secret"] = form_data.client_secret
    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 characters (:) or similar, and get the two parts items and read. Many applications do that to group and organize permissions, you could do it as well in your application, just know that that it is application specific, it's not part of the specification.

参数 描述
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.

类型: 联合类型[字符串, None] 默认值: None

username

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

类型: str

password

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

类型: 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

类型: str 默认值: ''

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.

类型: 联合类型[字符串, None] 默认值: 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.

类型: 联合类型[字符串, None] 默认值: None

Source code in fastapi/security/oauth2.py
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def __init__(
    self,
    *,
    grant_type: Annotated[
        Union[str, None],
        Form(pattern="^password$"),
        Doc(
            """
            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.
            """
        ),
    ] = None,
    username: Annotated[
        str,
        Form(),
        Doc(
            """
            `username` string. The OAuth2 spec requires the exact field name
            `username`.
            """
        ),
    ],
    password: Annotated[
        str,
        Form(json_schema_extra={"format": "password"}),
        Doc(
            """
            `password` string. The OAuth2 spec requires the exact field name
            `password`.
            """
        ),
    ],
    scope: Annotated[
        str,
        Form(),
        Doc(
            """
            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`
            """
        ),
    ] = "",
    client_id: Annotated[
        Union[str, None],
        Form(),
        Doc(
            """
            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.
            """
        ),
    ] = None,
    client_secret: Annotated[
        Union[str, None],
        Form(json_schema_extra={"format": "password"}),
        Doc(
            """
            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.
            """
        ),
    ] = None,
):
    self.grant_type = grant_type
    self.username = username
    self.password = password
    self.scopes = scope.split()
    self.client_id = client_id
    self.client_secret = client_secret

grant_type instance-attribute

grant_type = grant_type

username instance-attribute

username = username

password instance-attribute

password = password

scopes instance-attribute

scopes = split()

client_id instance-attribute

client_id = client_id

client_secret instance-attribute

client_secret = client_secret

fastapi.security.OAuth2PasswordRequestFormStrict

OAuth2PasswordRequestFormStrict(
    grant_type,
    username,
    password,
    scope="",
    client_id=None,
    client_secret=None,
)

Bases: 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.

OAuth2PasswordRequestFormStrictOAuth2PasswordRequestForm 的唯一区别在于,OAuth2PasswordRequestFormStrict 要求客户端发送 grant_type 表单字段,其值为 "password",这在 OAuth2 规范中是必需的(似乎没有特别的原因),而对于 OAuth2PasswordRequestFormgrant_type 是可选的。

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

示例

from typing import Annotated

from fastapi import Depends, FastAPI
from fastapi.security import OAuth2PasswordRequestForm

app = FastAPI()


@app.post("/login")
def login(form_data: Annotated[OAuth2PasswordRequestFormStrict, Depends()]):
    data = {}
    data["scopes"] = []
    for scope in form_data.scopes:
        data["scopes"].append(scope)
    if form_data.client_id:
        data["client_id"] = form_data.client_id
    if form_data.client_secret:
        data["client_secret"] = form_data.client_secret
    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 characters (:) or similar, and get the two parts items and read. Many applications do that to group and organize permissions, you could do it as well in your application, just know that that it is application specific, it's not part of the specification.

OAuth2 规范规定它是必需的,并且必须是固定字符串“password”。

此依赖项对此非常严格。如果您想宽松处理,请改用 OAuth2PasswordRequestForm 依赖类。

username: 用户名字符串。OAuth2 规范要求精确的字段名“username”。 password: 密码字符串。OAuth2 规范要求精确的字段名“password”。 scope: 可选字符串。多个范围(每个都是一个字符串),用空格分隔。例如“items:read items:write users:read profile openid” client_id: 可选字符串。OAuth2 建议使用 HTTP Basic 身份验证发送 client_id 和 client_secret(如果有),如下所示:client_id:client_secret client_secret: 可选字符串。OAuth2 建议使用 HTTP Basic 身份验证发送 client_id 和 client_secret(如果有),如下所示:client_id:client_secret

参数 描述
grant_type

OAuth2 规范规定它是必需的,并且必须是固定字符串“password”。此依赖项对此非常严格。如果您想宽松处理,请改用 OAuth2PasswordRequestForm 依赖类。

类型: str

username

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

类型: str

password

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

类型: 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

类型: str 默认值: ''

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.

类型: 联合类型[字符串, None] 默认值: 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.

类型: 联合类型[字符串, None] 默认值: None

Source code in fastapi/security/oauth2.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
def __init__(
    self,
    grant_type: Annotated[
        str,
        Form(pattern="^password$"),
        Doc(
            """
            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: Annotated[
        str,
        Form(),
        Doc(
            """
            `username` string. The OAuth2 spec requires the exact field name
            `username`.
            """
        ),
    ],
    password: Annotated[
        str,
        Form(),
        Doc(
            """
            `password` string. The OAuth2 spec requires the exact field name
            `password`.
            """
        ),
    ],
    scope: Annotated[
        str,
        Form(),
        Doc(
            """
            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`
            """
        ),
    ] = "",
    client_id: Annotated[
        Union[str, None],
        Form(),
        Doc(
            """
            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.
            """
        ),
    ] = None,
    client_secret: Annotated[
        Union[str, None],
        Form(),
        Doc(
            """
            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.
            """
        ),
    ] = None,
):
    super().__init__(
        grant_type=grant_type,
        username=username,
        password=password,
        scope=scope,
        client_id=client_id,
        client_secret=client_secret,
    )

grant_type 实例属性

grant_type = grant_type

username 实例属性

username = username

password 实例属性

password = password

scopes 实例属性

scopes = split()

client_id 实例属性

client_id = client_id

client_secret 实例属性

client_secret = client_secret

依赖项中的 OAuth2 安全范围

fastapi.security.SecurityScopes

SecurityScopes(scopes=None)

这是一个特殊的类,您可以在依赖项的参数中定义它,以获取同一链中所有依赖项所需的 OAuth2 范围。

这样,多个依赖项可以拥有不同的范围,即使它们在同一个路径操作中使用。通过这种方式,您可以在一个地方访问所有这些依赖项所需的范围。

有关详细信息,请参阅 FastAPI 的 OAuth2 范围文档

参数 描述
scopes

FastAPI 将填写此内容。

类型: Optional[list[str]] 默认值: None

Source code in fastapi/security/oauth2.py
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
def __init__(
    self,
    scopes: Annotated[
        Optional[list[str]],
        Doc(
            """
            This will be filled by FastAPI.
            """
        ),
    ] = None,
):
    self.scopes: Annotated[
        list[str],
        Doc(
            """
            The list of all the scopes required by dependencies.
            """
        ),
    ] = scopes or []
    self.scope_str: Annotated[
        str,
        Doc(
            """
            All the scopes required by all the dependencies in a single string
            separated by spaces, as defined in the OAuth2 specification.
            """
        ),
    ] = " ".join(self.scopes)

scopes 实例属性

scopes = scopes or []

依赖项所需的所有范围的列表。

scope_str 实例属性

scope_str = join(scopes)

所有依赖项所需的范围,以单个字符串形式,用空格分隔,如 OAuth2 规范中所定义。

OpenID Connect

fastapi.security.OpenIdConnect

OpenIdConnect(
    *,
    openIdConnectUrl,
    scheme_name=None,
    description=None,
    auto_error=True
)

Bases: SecurityBase

OpenID Connect 身份验证类。其实例将用作依赖项。

警告:这只是一个用于将组件与 FastAPI 中的 OpenAPI 连接的存根,它没有实现完整的 OpenIdConnect 方案,例如,它不使用 OpenIDConnect URL。您需要对其进行子类化并在您的代码中实现它。

参数 描述
openIdConnectUrl

OpenID Connect URL。

类型: str

scheme_name

Security scheme name.

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

类型: Optional[str] 默认值: None

description

Security scheme description.

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

类型: Optional[str] 默认值: None

auto_error

默认情况下,如果未提供 HTTP Authorization 头(对于 OpenID Connect 身份验证是必需的),它将自动取消请求并向客户端发送错误。

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.

当您希望身份验证可以通过多种可选方式之一提供时(例如,使用 OpenID Connect 或 Cookie),这也很有用。

类型: bool 默认值: True

源代码位于 fastapi/security/open_id_connect_url.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def __init__(
    self,
    *,
    openIdConnectUrl: Annotated[
        str,
        Doc(
            """
        The OpenID Connect URL.
        """
        ),
    ],
    scheme_name: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme name.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme description.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if no HTTP Authorization 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).
            """
        ),
    ] = True,
):
    self.model = OpenIdConnectModel(
        openIdConnectUrl=openIdConnectUrl, description=description
    )
    self.scheme_name = scheme_name or self.__class__.__name__
    self.auto_error = auto_error

model 实例属性

model = OpenIdConnect(
    openIdConnectUrl=openIdConnectUrl,
    description=description,
)

scheme_name 实例属性

scheme_name = scheme_name or __name__

auto_error 实例属性

auto_error = auto_error

make_not_authenticated_error

make_not_authenticated_error()
源代码位于 fastapi/security/open_id_connect_url.py
80
81
82
83
84
85
def make_not_authenticated_error(self) -> HTTPException:
    return HTTPException(
        status_code=HTTP_401_UNAUTHORIZED,
        detail="Not authenticated",
        headers={"WWW-Authenticate": "Bearer"},
    )