跳至內容

安全性工具

當您需要使用 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 金鑰驗證。

這定義了應該在請求中提供的 Cookie 名稱(包含 API 金鑰),並將其整合到 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}
參數 說明
name (名稱)

Cookie 名稱。

類型: str

scheme_name (機制名稱)

安全性機制名稱。

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

類型: Optional[str] 預設值: None

description (說明)

安全性機制說明。

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

類型: Optional[str] 預設值: None

auto_error (自動錯誤)

預設情況下,如果未提供 Cookie,APIKeyCookie 將自動取消請求並向用戶端發送錯誤訊息。

如果將 auto_error 設為 False,則在 Cookie 不可用時,依賴項結果將會是 None,而不是拋出錯誤。

這在您想要選擇性驗證時非常有用。

當您想要以多種選用方式之一提供驗證時(例如,在 Cookie 或 HTTP Bearer 權杖中),這也很有用。

類型: bool 預設值: True

原始程式碼位於 fastapi/security/api_key.py
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
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 實例屬性

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

scheme_name 實例屬性

scheme_name = scheme_name or __name__

auto_error 實例屬性

auto_error = auto_error

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}
參數 說明
name (名稱)

標頭名稱。

類型: str

scheme_name (機制名稱)

安全性機制名稱。

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

類型: Optional[str] 預設值: None

description (說明)

安全性機制說明。

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

類型: Optional[str] 預設值: None

auto_error (自動錯誤)

預設情況下,如果未提供標頭,APIKeyHeader 將自動取消請求並向用戶端發送錯誤訊息。

如果將 auto_error 設為 False,則在標頭不 उपलब्ध 時,依賴項結果將會是 None,而不是拋出錯誤。

這在您想要選擇性驗證時非常有用。

當您想要以多種選用方式之一提供驗證時(例如,在標頭或 HTTP Bearer 權杖中),這也很有用。

類型: bool 預設值: True

原始程式碼位於 fastapi/security/api_key.py
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
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 實例屬性

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

scheme_name 實例屬性

scheme_name = scheme_name or __name__

auto_error 實例屬性

auto_error = auto_error

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}
參數 說明
name (名稱)

查詢參數名稱。

類型: str

scheme_name (機制名稱)

安全性機制名稱。

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

類型: Optional[str] 預設值: None

description (說明)

安全性機制說明。

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

類型: Optional[str] 預設值: None

auto_error (自動錯誤)

預設情況下,如果未提供查詢參數,`APIKeyQuery` 將自動取消請求並向客戶端發送錯誤。

如果將 `auto_error` 設定為 `False`,則當查詢參數不可用時,依賴項結果將為 `None`,而不是拋出錯誤。

這在您想要選擇性驗證時非常有用。

當您希望以多種可選方式之一提供身份驗證時(例如,在查詢參數中或在 HTTP Bearer 權杖中),這也很有用。

類型: bool 預設值: True

原始程式碼位於 fastapi/security/api_key.py
 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
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
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 實例屬性

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

scheme_name 實例屬性

scheme_name = scheme_name or __name__

auto_error 實例屬性

auto_error = auto_error

HTTP 驗證機制

fastapi.security.HTTPBasic

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

基底: HTTPBase

HTTP 基本驗證。

用法

建立一個實例物件,並將該物件用作 Depends() 中的依賴項。

依賴項結果將是一個包含 `username` 和 `password` 的 `HTTPBasicCredentials` 物件。

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

realm

HTTP 基本驗證領域。

類型: Optional[str] 預設值: None

description (說明)

安全性機制說明。

它將包含在生成的 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 實例屬性

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

scheme_name 實例屬性

scheme_name = scheme_name or __name__

realm 實例屬性

realm = realm

auto_error 實例屬性

auto_error = auto_error

fastapi.security.HTTPBearer

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

基底: HTTPBase

HTTP Bearer 權杖驗證。

用法

建立一個實例物件,並將該物件用作 Depends() 中的依賴項。

相依性結果將會是一個包含 scheme(驗證機制)和 credentials(憑證)的 HTTPAuthorizationCredentials 物件。

範例

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

description (說明)

安全性機制說明。

它將包含在生成的 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 Digest 驗證。

用法

建立一個實例物件,並將該物件用作 Depends() 中的依賴項。

相依性結果將會是一個包含 scheme(驗證機制)和 credentials(憑證)的 HTTPAuthorizationCredentials 物件。

範例

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

description (說明)

安全性機制說明。

它將包含在生成的 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 實例屬性

scheme

從標頭值中提取的 HTTP 授權方案。

credentials 實例屬性

credentials

從標頭值中提取的 HTTP 授權憑證。

fastapi.security.HTTPBasicCredentials

基底:BaseModel

在 dependency 中使用 HTTPBasic 後所提供的 HTTP 基本驗證憑證。

FastAPI 的 HTTP 基本驗證文件中了解更多資訊。

username 實例屬性

username

HTTP 基本驗證的使用者名稱。

password 實例屬性

password

HTTP 基本驗證的密碼。

OAuth2 驗證

fastapi.security.OAuth2

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

基底類別: SecurityBase

這是 OAuth2 驗證的基底類別,它的實例將會被用作 dependency。所有其他的 OAuth2 類別都繼承自它,並針對每個 OAuth2 流程進行客製化。

您通常不會建立一個繼承自它的新類別,而是使用現有的子類別之一,如果您想支援多個流程,則可以組合它們。

FastAPI 安全性文件 中了解更多相關資訊。

參數 說明
flows(流程)

OAuth2 流程的字典。

類型: Union[OAuthFlows, Dict[str, Dict[str, Any]]] 預設值: OAuthFlows()

scheme_name (機制名稱)

安全性機制名稱。

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

類型: Optional[str] 預設值: None

description (說明)

安全性機制說明。

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

類型: Optional[str] 預設值: None

auto_error (自動錯誤)

預設情況下,如果沒有提供 HTTP 授權標頭(OAuth2 驗證所需),它會自動取消請求並向客戶端發送錯誤訊息。

如果將 auto_error 設為 False,當 HTTP 授權標頭不可用時,dependency 的結果將會是 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 實例屬性

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

scheme_name 實例屬性

scheme_name = scheme_name or __name__

auto_error 實例屬性

auto_error = auto_error

fastapi.security.OAuth2AuthorizationCodeBearer

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

基底類別: OAuth2

使用透過 OAuth2 授權碼流程取得的 bearer token 進行驗證的 OAuth2 流程。其實例將被用作依賴項。

參數 說明
authorizationUrl

類型: str

tokenUrl

獲取 OAuth2 token 的網址。

類型: str

refreshUrl

重新整理 token 並取得新 token 的網址。

類型: Optional[str] 預設值: None

scheme_name (機制名稱)

安全性機制名稱。

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

類型: Optional[str] 預設值: None

scopes

使用此依賴項的*路徑操作*所需的 OAuth2 範圍。

類型: Optional[Dict[str, str]] 預設值: None

description (說明)

安全性機制說明。

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

類型: Optional[str] 預設值: None

auto_error (自動錯誤)

預設情況下,如果沒有提供 HTTP 授權標頭(OAuth2 驗證所需),它會自動取消請求並向客戶端發送錯誤訊息。

如果將 auto_error 設為 False,當 HTTP 授權標頭不可用時,dependency 的結果將會是 None,而不是拋出錯誤。

這在您想要選擇性驗證時非常有用。

當您希望以多種可選方式之一提供驗證時(例如,使用 OAuth2 或 cookie),這也很有用。

類型: bool 預設值: True

原始碼位於 fastapi/security/oauth2.py
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
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
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 實例屬性

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

scheme_name 實例屬性

scheme_name = scheme_name or __name__

auto_error 實例屬性

auto_error = auto_error

fastapi.security.OAuth2PasswordBearer

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

基底類別: OAuth2

使用透過密碼取得的 bearer token 進行驗證的 OAuth2 流程。其實例將被用作依賴項。

FastAPI 簡單 OAuth2 搭配密碼與 Bearer 文件中了解更多資訊。

參數 說明
tokenUrl

獲取 OAuth2 token 的網址。這將是具有 OAuth2PasswordRequestForm 作為依賴項的*路徑操作*。

類型: str

scheme_name (機制名稱)

安全性機制名稱。

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

類型: Optional[str] 預設值: None

scopes

使用此依賴項的*路徑操作*所需的 OAuth2 範圍。

類型: Optional[Dict[str, str]] 預設值: None

description (說明)

安全性機制說明。

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

類型: Optional[str] 預設值: None

auto_error (自動錯誤)

預設情況下,如果沒有提供 HTTP 授權標頭(OAuth2 驗證所需),它會自動取消請求並向客戶端發送錯誤訊息。

如果將 auto_error 設為 False,當 HTTP 授權標頭不可用時,dependency 的結果將會是 None,而不是拋出錯誤。

這在您想要選擇性驗證時非常有用。

當您希望以多種可選方式之一提供驗證時(例如,使用 OAuth2 或 cookie),這也很有用。

類型: bool 預設值: True

原始碼位於 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
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,
):
    if not scopes:
        scopes = {}
    flows = OAuthFlowsModel(
        password=cast(Any, {"tokenUrl": tokenUrl, "scopes": scopes})
    )
    super().__init__(
        flows=flows,
        scheme_name=scheme_name,
        description=description,
        auto_error=auto_error,
    )

model 實例屬性

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

scheme_name 實例屬性

scheme_name = scheme_name or __name__

auto_error 實例屬性

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 簡單 OAuth2 搭配密碼與 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[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 兩部分。許多應用程式都這樣做來分組和組織權限,您也可以在您的應用程式中這樣做,只需知道這是應用程式特定的,它不是規範的一部分。

參數 說明
grant_type

OAuth2 規範說明這是必要的,而且**必須**是固定字串 "password"。然而,這個依賴類別是允許的,允許不傳遞它。如果您想要強制執行,請改用 OAuth2PasswordRequestFormStrict 依賴項。

類型: Union[str, None] 預設值: None

username

username 字串。OAuth2 規範要求確切的欄位名稱為 username

類型: str

password

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 基本驗證發送 client_idclient_secret(如果有的話)。

類型: Union[str, None] 預設值: None

client_secret

如果存在 client_password(以及 client_id),它們可以作為表單欄位的一部分發送。但 OAuth2 規範建議使用 HTTP 基本驗證發送 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(),
        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,
):
    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 實例屬性

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

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 簡單 OAuth2 搭配密碼與 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

請注意,對於 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

參數 說明
grant_type

OAuth2 規範說明這是必需的,而且必須是固定字串 "password"。這個依賴項對此很嚴格。如果您想要寬鬆一些,請改用 OAuth2PasswordRequestForm 依賴項類別。

類型: str

username

username 字串。OAuth2 規範要求確切的欄位名稱為 username

類型: str

password

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 基本驗證發送 client_idclient_secret(如果有的話)。

類型: Union[str, None] 預設值: None

client_secret

如果存在 client_password(以及 client_id),它們可以作為表單欄位的一部分發送。但 OAuth2 規範建議使用 HTTP 基本驗證發送 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 實例屬性

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

原始碼位於 fastapi/security/oauth2.py
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
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
)

基底類別: SecurityBase

OpenID Connect 驗證類別。它的實例將被用作依賴項。

參數 說明
openIdConnectUrl

OpenID Connect 的 URL。

類型: str

scheme_name (機制名稱)

安全性機制名稱。

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

類型: Optional[str] 預設值: None

description (說明)

安全性機制說明。

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

類型: Optional[str] 預設值: None

auto_error (自動錯誤)

預設情況下,如果沒有提供 OpenID Connect 驗證所需的 HTTP 授權標頭,它會自動取消請求並向用戶端發送錯誤訊息。

如果將 auto_error 設為 False,當 HTTP 授權標頭不可用時,dependency 的結果將會是 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 實例屬性

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

scheme_name 實例屬性

scheme_name = scheme_name or __name__

auto_error 實例屬性

auto_error = auto_error