跳到内容

安全工具

当你需要声明带有 OAuth2 范围的依赖时,可以使用 Security()

但是你仍然需要定义可依赖项,即作为参数传递给 Depends()Security() 的可调用对象。

有多种工具可以用来创建这些可依赖项,它们被集成到 OpenAPI 中,以便在自动文档 UI 中显示,可供自动生成的客户端和 SDK 等使用。

你可以从 fastapi.security 导入它们

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

API 密钥安全方案

fastapi.security.APIKeyCookie

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

基类: APIKeyBase

使用 cookie 进行 API 密钥认证。

这定义了请求中应包含 API 密钥的 cookie 名称,并将其集成到 OpenAPI 文档中。它会自动提取 cookie 中发送的密钥值,并将其作为依赖结果提供。但它不定义如何设置该 cookie。

用法

创建一个实例对象,并将其用作 Depends() 中的依赖项。

依赖结果将是一个包含密钥值的字符串。

示例

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}
参数 描述
名称

Cookie 名称。

类型: str

scheme_name

安全方案名称。

它将包含在生成的 OpenAPI 中(例如,在 /docs 中可见)。

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

描述

安全方案描述。

它将包含在生成的 OpenAPI 中(例如,在 /docs 中可见)。

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

auto_error

默认情况下,如果未提供 cookie,APIKeyCookie 将自动取消请求并向客户端发送错误。

如果 auto_error 设置为 False,当 cookie 不可用时,依赖结果将为 None,而不是报错。

这在您想要可选认证时很有用。

当您希望认证可以通过多种可选方式提供时(例如,在 cookie 中或在 HTTP Bearer 令牌中),它也很有用。

类型: bool 默认值: True

源代码位于 fastapi/security/api_key.py
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
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,
):
    self.model: APIKey = APIKey(
        **{"in": APIKeyIn.cookie},  # type: ignore[arg-type]
        name=name,
        description=description,
    )
    self.scheme_name = scheme_name or self.__class__.__name__
    self.auto_error = auto_error

model instance-attribute

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

scheme_name instance-attribute

scheme_name = scheme_name or __name__

auto_error instance-attribute

auto_error = auto_error

check_api_key staticmethod

check_api_key(api_key, auto_error)
源代码位于 fastapi/security/api_key.py
12
13
14
15
16
17
18
19
20
@staticmethod
def check_api_key(api_key: Optional[str], auto_error: bool) -> Optional[str]:
    if not api_key:
        if auto_error:
            raise HTTPException(
                status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
            )
        return None
    return api_key

fastapi.security.APIKeyHeader

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

基类: APIKeyBase

使用请求头进行 API 密钥认证。

这定义了请求中应包含 API 密钥的请求头名称,并将其集成到 OpenAPI 文档中。它会自动提取请求头中发送的密钥值,并将其作为依赖结果提供。但它不定义如何将该密钥发送给客户端。

用法

创建一个实例对象,并将其用作 Depends() 中的依赖项。

依赖结果将是一个包含密钥值的字符串。

示例

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}
参数 描述
名称

请求头名称。

类型: str

scheme_name

安全方案名称。

它将包含在生成的 OpenAPI 中(例如,在 /docs 中可见)。

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

描述

安全方案描述。

它将包含在生成的 OpenAPI 中(例如,在 /docs 中可见)。

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

auto_error

默认情况下,如果未提供请求头,APIKeyHeader 将自动取消请求并向客户端发送错误。

如果 auto_error 设置为 False,当请求头不可用时,依赖结果将为 None,而不是报错。

这在您想要可选认证时很有用。

当您希望认证可以通过多种可选方式提供时(例如,在请求头中或在 HTTP Bearer 令牌中),它也很有用。

类型: bool 默认值: True

源代码位于 fastapi/security/api_key.py
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
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,
):
    self.model: APIKey = APIKey(
        **{"in": APIKeyIn.header},  # type: ignore[arg-type]
        name=name,
        description=description,
    )
    self.scheme_name = scheme_name or self.__class__.__name__
    self.auto_error = auto_error

model instance-attribute

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

scheme_name instance-attribute

scheme_name = scheme_name or __name__

auto_error instance-attribute

auto_error = auto_error

check_api_key staticmethod

check_api_key(api_key, auto_error)
源代码位于 fastapi/security/api_key.py
12
13
14
15
16
17
18
19
20
@staticmethod
def check_api_key(api_key: Optional[str], auto_error: bool) -> Optional[str]:
    if not api_key:
        if auto_error:
            raise HTTPException(
                status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
            )
        return None
    return api_key

fastapi.security.APIKeyQuery

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

基类: APIKeyBase

使用查询参数进行 API 密钥认证。

这定义了请求中应包含 API 密钥的查询参数名称,并将其集成到 OpenAPI 文档中。它会自动提取查询参数中发送的密钥值,并将其作为依赖结果提供。但它不定义如何将该 API 密钥发送给客户端。

用法

创建一个实例对象,并将其用作 Depends() 中的依赖项。

依赖结果将是一个包含密钥值的字符串。

示例

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}
参数 描述
名称

查询参数名称。

类型: str

scheme_name

安全方案名称。

它将包含在生成的 OpenAPI 中(例如,在 /docs 中可见)。

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

描述

安全方案描述。

它将包含在生成的 OpenAPI 中(例如,在 /docs 中可见)。

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

auto_error

默认情况下,如果未提供查询参数,APIKeyQuery 将自动取消请求并向客户端发送错误。

如果 auto_error 设置为 False,当查询参数不可用时,依赖结果将为 None,而不是报错。

这在您想要可选认证时很有用。

当您希望认证可以通过多种可选方式提供时(例如,在查询参数中或在 HTTP Bearer 令牌中),它也很有用。

类型: bool 默认值: True

源代码位于 fastapi/security/api_key.py
 55
 56
 57
 58
 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
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,
):
    self.model: APIKey = APIKey(
        **{"in": APIKeyIn.query},  # type: ignore[arg-type]
        name=name,
        description=description,
    )
    self.scheme_name = scheme_name or self.__class__.__name__
    self.auto_error = auto_error

model instance-attribute

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

scheme_name instance-attribute

scheme_name = scheme_name or __name__

auto_error instance-attribute

auto_error = auto_error

check_api_key staticmethod

check_api_key(api_key, auto_error)
源代码位于 fastapi/security/api_key.py
12
13
14
15
16
17
18
19
20
@staticmethod
def check_api_key(api_key: Optional[str], auto_error: bool) -> Optional[str]:
    if not api_key:
        if auto_error:
            raise HTTPException(
                status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
            )
        return None
    return api_key

HTTP 认证方案

fastapi.security.HTTPBasic

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

基类: HTTPBase

HTTP 基本认证。

用法

创建一个实例对象,并将其用作 Depends() 中的依赖项。

依赖结果将是一个包含 usernamepasswordHTTPBasicCredentials 对象。

FastAPI 关于 HTTP 基本认证的文档中阅读更多信息。

示例

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

安全方案名称。

它将包含在生成的 OpenAPI 中(例如,在 /docs 中可见)。

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

领域

HTTP 基本认证领域。

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

描述

安全方案描述。

它将包含在生成的 OpenAPI 中(例如,在 /docs 中可见)。

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

auto_error

默认情况下,如果未提供 HTTP 基本认证(请求头),HTTPBasic 将自动取消请求并向客户端发送错误。

如果 auto_error 设置为 False,当 HTTP 基本认证不可用时,依赖结果将为 None,而不是报错。

这在您想要可选认证时很有用。

当您希望认证可以通过多种可选方式提供时(例如,通过 HTTP 基本认证或通过 HTTP Bearer 令牌),它也很有用。

类型: bool 默认值: True

源代码位于 fastapi/security/http.py
130
131
132
133
134
135
136
137
138
139
140
141
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
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

fastapi.security.HTTPBearer

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

基类: HTTPBase

HTTP Bearer 令牌认证。

用法

创建一个实例对象,并将其用作 Depends() 中的依赖项。

依赖结果将是一个包含 schemecredentialsHTTPAuthorizationCredentials 对象。

示例

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 令牌格式。

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

scheme_name

安全方案名称。

它将包含在生成的 OpenAPI 中(例如,在 /docs 中可见)。

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

描述

安全方案描述。

它将包含在生成的 OpenAPI 中(例如,在 /docs 中可见)。

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

auto_error

默认情况下,如果未提供 HTTP Bearer 令牌(在 Authorization 头中),HTTPBearer 将自动取消请求并向客户端发送错误。

如果 auto_error 设置为 False,当 HTTP Bearer 令牌不可用时,依赖结果将为 None,而不是报错。

这在您想要可选认证时很有用。

当您希望认证可以通过多种可选方式提供时(例如,在 HTTP Bearer 令牌中或在 cookie 中),它也很有用。

类型: bool 默认值: True

源代码位于 fastapi/security/http.py
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
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

fastapi.security.HTTPDigest

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

基类: HTTPBase

HTTP 摘要认证。

用法

创建一个实例对象,并将其用作 Depends() 中的依赖项。

依赖结果将是一个包含 schemecredentialsHTTPAuthorizationCredentials 对象。

示例

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

安全方案名称。

它将包含在生成的 OpenAPI 中(例如,在 /docs 中可见)。

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

描述

安全方案描述。

它将包含在生成的 OpenAPI 中(例如,在 /docs 中可见)。

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

auto_error

默认情况下,如果未提供 HTTP Digest,HTTPDigest 将自动取消请求并向客户端发送错误。

如果 auto_error 设置为 False,当 HTTP Digest 不可用时,依赖结果将为 None,而不是报错。

这在您想要可选认证时很有用。

当您希望认证可以通过多种可选方式提供时(例如,通过 HTTP Digest 或通过 cookie),它也很有用。

类型: bool 默认值: True

源代码位于 fastapi/security/http.py
356
357
358
359
360
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
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

HTTP 凭据

fastapi.security.HTTPAuthorizationCredentials

基类: BaseModel

作为在依赖项中使用 HTTPBearerHTTPDigest 的结果,返回的 HTTP 授权凭据。

HTTP 授权头值通过第一个空格分隔。

第一部分是 scheme,第二部分是 credentials

例如,在 HTTP Bearer 令牌方案中,客户端将发送如下请求头:

Authorization: Bearer deadbeef12346

在这种情况下

  • scheme 将具有值 "Bearer"
  • credentials 将具有值 "deadbeef12346"

scheme instance-attribute

scheme

从请求头值中提取的 HTTP 授权方案。

credentials instance-attribute

credentials

从请求头值中提取的 HTTP 授权凭据。

fastapi.security.HTTPBasicCredentials

基类: BaseModel

作为在依赖项中使用 HTTPBasic 的结果返回的 HTTP 基本凭据。

FastAPI 关于 HTTP 基本认证的文档中阅读更多信息。

username instance-attribute

username

HTTP 基本认证用户名。

password instance-attribute

password

HTTP 基本认证密码。

OAuth2 认证

fastapi.security.OAuth2

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

基类: SecurityBase

这是 OAuth2 认证的基类,它的一个实例将用作依赖。所有其他 OAuth2 类都继承自它,并针对每个 OAuth2 流程对其进行自定义。

通常你不会创建一个继承自它的新类,而是使用现有的子类之一,如果你想支持多个流程,则可以组合它们。

FastAPI 关于安全性的文档中阅读更多信息。

参数 描述
流程

OAuth2 流程的字典。

类型: Union[OAuthFlows, Dict[str, Dict[str, Any]]] 默认值: OAuthFlows()

scheme_name

安全方案名称。

它将包含在生成的 OpenAPI 中(例如,在 /docs 中可见)。

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

描述

安全方案描述。

它将包含在生成的 OpenAPI 中(例如,在 /docs 中可见)。

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

auto_error

默认情况下,如果未提供 OAuth2 认证所需的 HTTP Authorization 头,它将自动取消请求并向客户端发送错误。

如果 auto_error 设置为 False,当 HTTP Authorization 头不可用时,依赖结果将为 None,而不是报错。

这在您想要可选认证时很有用。

当您希望认证可以通过多种可选方式提供时(例如,通过 OAuth2 或通过 cookie),它也很有用。

类型: bool 默认值: True

源代码位于 fastapi/security/oauth2.py
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
376
377
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

fastapi.security.OAuth2AuthorizationCodeBearer

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

基类: OAuth2

OAuth2 认证流程,使用通过 OAuth2 授权码流程获得的 bearer 令牌。其一个实例将用作依赖项。

参数 描述
tokenUrl

获取 OAuth2 令牌的 URL。

类型: str

refreshUrl

刷新令牌并获取新令牌的 URL。

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

scheme_name

安全方案名称。

它将包含在生成的 OpenAPI 中(例如,在 /docs 中可见)。

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

scopes

使用此依赖项的路径操作所需的 OAuth2 范围。

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

描述

安全方案描述。

它将包含在生成的 OpenAPI 中(例如,在 /docs 中可见)。

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

auto_error

默认情况下,如果未提供 OAuth2 认证所需的 HTTP Authorization 头,它将自动取消请求并向客户端发送错误。

如果 auto_error 设置为 False,当 HTTP Authorization 头不可用时,依赖结果将为 None,而不是报错。

这在您想要可选认证时很有用。

当您希望认证可以通过多种可选方式提供时(例如,通过 OAuth2 或通过 cookie),它也很有用。

类型: bool 默认值: True

源代码位于 fastapi/security/oauth2.py
509
510
511
512
513
514
515
516
517
518
519
520
521
522
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
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

fastapi.security.OAuth2PasswordBearer

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

基类: OAuth2

OAuth2 认证流程,使用通过密码获得的 bearer 令牌。其一个实例将用作依赖项。

FastAPI 关于使用密码和 Bearer 令牌进行简单 OAuth2 认证的文档中阅读更多信息。

参数 描述
tokenUrl

获取 OAuth2 令牌的 URL。这将是使用 OAuth2PasswordRequestForm 作为依赖项的路径操作

类型: str

scheme_name

安全方案名称。

它将包含在生成的 OpenAPI 中(例如,在 /docs 中可见)。

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

scopes

使用此依赖项的路径操作所需的 OAuth2 范围。

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

描述

安全方案描述。

它将包含在生成的 OpenAPI 中(例如,在 /docs 中可见)。

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

auto_error

默认情况下,如果未提供 OAuth2 认证所需的 HTTP Authorization 头,它将自动取消请求并向客户端发送错误。

如果 auto_error 设置为 False,当 HTTP Authorization 头不可用时,依赖结果将为 None,而不是报错。

这在您想要可选认证时很有用。

当您希望认证可以通过多种可选方式提供时(例如,通过 OAuth2 或通过 cookie),它也很有用。

类型: bool 默认值: True

refreshUrl

刷新令牌并获取新令牌的 URL。

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

源代码位于 fastapi/security/oauth2.py
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
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
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

OAuth2 密码表单

fastapi.security.OAuth2PasswordRequestForm

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

这是一个依赖类,用于收集 OAuth2 密码流程的表单数据中的 usernamepassword

OAuth2 规范规定,对于密码流程,数据应使用表单数据(而不是 JSON)进行收集,并且应具有特定的字段 usernamepassword

所有初始化参数都从请求中提取。

FastAPI 关于使用密码和 Bearer 令牌进行简单 OAuth2 认证的文档中阅读更多信息。

示例

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

请注意,对于 OAuth2,范围 items:read 是一个不透明字符串中的单个范围。您可以自定义内部逻辑,通过冒号字符(:)或类似方式将其分开,并获取 itemsread 两部分。许多应用程序都这样做来对权限进行分组和组织,您也可以在您的应用程序中这样做,只需知道这是应用程序特定的,不属于规范的一部分。

参数 描述
授权类型

OAuth2 规范指出它是必需的,并且必须是固定字符串 "password"。然而,这个依赖类是宽松的,允许不传递它。如果您想强制执行它,请改用 OAuth2PasswordRequestFormStrict 依赖项。

类型: Union[str, None] 默认值: None

用户名

username 字符串。OAuth2 规范要求字段名必须是 username

类型: str

密码

password 字符串。OAuth2 规范要求字段名必须是 `password"。

类型: str

scope

一个由空格分隔的字符串,包含多个范围。每个范围也是一个字符串。

例如,一个包含以下内容的字符串

```python "items:read items:write users:read profile openid" ````

将表示以下范围

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

类型: str 默认值: ''

client_id

如果存在 client_id,它可以作为表单字段的一部分发送。但 OAuth2 规范建议使用 HTTP Basic 认证发送 client_idclient_secret(如果存在)。

类型: Union[str, None] 默认值: None

client_secret

如果存在 client_password(和 client_id),它们可以作为表单字段的一部分发送。但是 OAuth2 规范建议使用 HTTP Basic 认证发送 client_idclient_secret(如果存在)。

类型: Union[str, None] 默认值: None

源代码位于 fastapi/security/oauth2.py
 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
148
149
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,
)

基类: OAuth2PasswordRequestForm

这是一个依赖类,用于收集 OAuth2 密码流程的表单数据中的 usernamepassword

OAuth2 规范规定,对于密码流程,数据应使用表单数据(而不是 JSON)进行收集,并且应具有特定的字段 usernamepassword

所有初始化参数都从请求中提取。

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

FastAPI 关于使用密码和 Bearer 令牌进行简单 OAuth2 认证的文档中阅读更多信息。

示例

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

请注意,对于 OAuth2,范围 items:read 是一个不透明字符串中的单个范围。您可以自定义内部逻辑,通过冒号字符(:)或类似方式将其分开,并获取 itemsread 两部分。许多应用程序都这样做来对权限进行分组和组织,您也可以在您的应用程序中这样做,只需知道这是应用程序特定的,不属于规范的一部分。

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

参数 描述
授权类型

OAuth2 规范规定它是必需的,并且必须是固定字符串 "password"。此依赖项对此要求严格。如果您希望宽松处理,请改用 OAuth2PasswordRequestForm 依赖类。

类型: str

用户名

username 字符串。OAuth2 规范要求字段名必须是 username

类型: str

密码

password 字符串。OAuth2 规范要求字段名必须是 `password"。

类型: str

scope

一个由空格分隔的字符串,包含多个范围。每个范围也是一个字符串。

例如,一个包含以下内容的字符串

```python "items:read items:write users:read profile openid" ````

将表示以下范围

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

类型: str 默认值: ''

client_id

如果存在 client_id,它可以作为表单字段的一部分发送。但 OAuth2 规范建议使用 HTTP Basic 认证发送 client_idclient_secret(如果存在)。

类型: Union[str, None] 默认值: None

client_secret

如果存在 client_password(和 client_id),它们可以作为表单字段的一部分发送。但是 OAuth2 规范建议使用 HTTP Basic 认证发送 client_idclient_secret(如果存在)。

类型: Union[str, None] 默认值: None

源代码位于 fastapi/security/oauth2.py
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
304
305
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 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

依赖中的 OAuth2 安全范围

fastapi.security.SecurityScopes

SecurityScopes(scopes=None)

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

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

FastAPI 关于 OAuth2 范围的文档中阅读更多信息。

参数 描述
scopes

这将被 FastAPI 填充。

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

源代码位于 fastapi/security/oauth2.py
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
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 instance-attribute

scopes = scopes or []

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

scope_str instance-attribute

scope_str = join(scopes)

所有依赖项所需的所有范围,由空格分隔成一个字符串,如 OAuth2 规范所定义。

OpenID Connect

fastapi.security.OpenIdConnect

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

基类: SecurityBase

OpenID Connect 认证类。其一个实例将用作依赖项。

参数 描述
openIdConnectUrl

OpenID Connect URL。

类型: str

scheme_name

安全方案名称。

它将包含在生成的 OpenAPI 中(例如,在 /docs 中可见)。

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

描述

安全方案描述。

它将包含在生成的 OpenAPI 中(例如,在 /docs 中可见)。

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

auto_error

默认情况下,如果未提供 OpenID Connect 认证所需的 HTTP Authorization 头,它将自动取消请求并向客户端发送错误。

如果 auto_error 设置为 False,当 HTTP Authorization 头不可用时,依赖结果将为 None,而不是报错。

这在您想要可选认证时很有用。

当您希望认证可以通过多种可选方式提供时(例如,通过 OpenID Connect 或通过 cookie),它也很有用。

类型: bool 默认值: True

源代码位于 fastapi/security/open_id_connect_url.py
17
18
19
20
21
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
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 instance-attribute

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

scheme_name instance-attribute

scheme_name = scheme_name or __name__

auto_error instance-attribute

auto_error = auto_error