コンテンツへスキップ

セキュリティツール

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

クッキーを使用したAPIキー認証。

これは、APIキーと一緒にリクエストで提供されるべきクッキーの名前を定義し、それをOpenAPIドキュメントに統合します。クッキーで送信されたキー値を自動的に抽出し、それを依存関係の結果として提供します。しかし、そのクッキーをどのように設定するかは定義しません。

使用法

インスタンスオブジェクトを作成し、そのオブジェクトを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

クッキー名。

型: str

scheme_name

セキュリティスキーム名。

生成されたOpenAPIに含まれます(例: /docsで表示されます)。

型: Optional[str] デフォルト: None

description

セキュリティスキームの説明。

生成されたOpenAPIに含まれます(例: /docsで表示されます)。

型: Optional[str] デフォルト: None

auto_error

デフォルトでは、クッキーが提供されていない場合、APIKeyCookieは自動的にリクエストをキャンセルし、クライアントにエラーを送信します。

auto_errorFalseに設定されている場合、クッキーが利用できないとき、エラーを出す代わりに、依存関係の結果はNoneになります。

これは、オプションの認証を設定したい場合に便利です。

また、複数のオプションの方法(例えば、クッキーまたはHTTPベアラトークン)で認証を提供したい場合にも便利です。

タイプ: 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 インスタンス属性

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

scheme_name インスタンス属性

scheme_name = scheme_name or __name__

auto_error インスタンス属性

auto_error = auto_error

check_api_key 静的メソッド

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}
パラメータ 説明
name

ヘッダー名。

型: str

scheme_name

セキュリティスキーム名。

生成されたOpenAPIに含まれます(例: /docsで表示されます)。

型: Optional[str] デフォルト: None

description

セキュリティスキームの説明。

生成されたOpenAPIに含まれます(例: /docsで表示されます)。

型: Optional[str] デフォルト: None

auto_error

デフォルトでは、ヘッダーが提供されていない場合、APIKeyHeaderは自動的にリクエストをキャンセルし、クライアントにエラーを送信します。

auto_errorFalseに設定されている場合、ヘッダーが利用できないとき、エラーを出す代わりに、依存関係の結果はNoneになります。

これは、オプションの認証を設定したい場合に便利です。

また、複数のオプションの方法(例えば、ヘッダーまたはHTTPベアラトークン)で認証を提供したい場合にも便利です。

タイプ: 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 インスタンス属性

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

scheme_name インスタンス属性

scheme_name = scheme_name or __name__

auto_error インスタンス属性

auto_error = auto_error

check_api_key 静的メソッド

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}
パラメータ 説明
name

クエリパラメータ名。

型: str

scheme_name

セキュリティスキーム名。

生成されたOpenAPIに含まれます(例: /docsで表示されます)。

型: Optional[str] デフォルト: None

description

セキュリティスキームの説明。

生成されたOpenAPIに含まれます(例: /docsで表示されます)。

型: Optional[str] デフォルト: None

auto_error

デフォルトでは、クエリパラメータが提供されていない場合、APIKeyQueryは自動的にリクエストをキャンセルし、クライアントにエラーを送信します。

auto_errorFalseに設定されている場合、クエリパラメータが利用できないとき、エラーを出す代わりに、依存関係の結果はNoneになります。

これは、オプションの認証を設定したい場合に便利です。

また、複数のオプションの方法(例えば、クエリパラメータまたはHTTPベアラトークン)で認証を提供したい場合にも便利です。

タイプ: 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 インスタンス属性

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

scheme_name インスタンス属性

scheme_name = scheme_name or __name__

auto_error インスタンス属性

auto_error = auto_error

check_api_key 静的メソッド

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()の依存関係として使用します。

依存関係の結果は、usernamepasswordを含むHTTPBasicCredentialsオブジェクトになります。

HTTPベーシック認証のFastAPIドキュメントで詳細を読むことができます。

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_errorFalseに設定されている場合、HTTPベーシック認証が利用できないとき、エラーを出す代わりに、依存関係の結果はNoneになります。

これは、オプションの認証を設定したい場合に便利です。

また、複数のオプションの方法(例えば、HTTPベーシック認証またはHTTPベアラトークン)で認証を提供したい場合にも便利です。

タイプ: 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ベアラトークン認証。

使用法

インスタンスオブジェクトを作成し、そのオブジェクトをDepends()の依存関係として使用します。

依存関係の結果は、schemecredentialsを含む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

ベアラトークン形式。

型: Optional[str] デフォルト: None

scheme_name

セキュリティスキーム名。

生成されたOpenAPIに含まれます(例: /docsで表示されます)。

型: Optional[str] デフォルト: None

description

セキュリティスキームの説明。

生成されたOpenAPIに含まれます(例: /docsで表示されます)。

型: Optional[str] デフォルト: None

auto_error

デフォルトでは、HTTPベアラトークンが提供されていない場合(Authorizationヘッダー)、HTTPBearerは自動的にリクエストをキャンセルし、クライアントにエラーを送信します。

auto_errorFalseに設定されている場合、HTTPベアラトークンが利用できないとき、エラーを出す代わりに、依存関係の結果はNoneになります。

これは、オプションの認証を設定したい場合に便利です。

また、複数のオプションの方法(例えば、HTTPベアラトークンまたはクッキー)で認証を提供したい場合にも便利です。

タイプ: 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 インスタンス属性

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

scheme_name インスタンス属性

scheme_name = scheme_name or __name__

auto_error インスタンス属性

auto_error = auto_error

fastapi.security.HTTPDigest

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

ベース: HTTPBase

HTTPダイジェスト認証。

使用法

インスタンスオブジェクトを作成し、そのオブジェクトをDepends()の依存関係として使用します。

依存関係の結果は、schemecredentialsを含む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ダイジェストが提供されていない場合、HTTPDigestは自動的にリクエストをキャンセルし、クライアントにエラーを送信します。

auto_errorFalseに設定されている場合、HTTPダイジェストが利用できないとき、エラーを出す代わりに、依存関係の結果はNoneになります。

これは、オプションの認証を設定したい場合に便利です。

また、複数のオプションの方法(例えば、HTTPダイジェストまたはクッキー)で認証を提供したい場合にも便利です。

タイプ: 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 インスタンス属性

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

scheme_name インスタンス属性

scheme_name = scheme_name or __name__

auto_error インスタンス属性

auto_error = auto_error

HTTP資格情報

fastapi.security.HTTPAuthorizationCredentials

ベース: BaseModel

依存関係でHTTPBearerまたはHTTPDigestを使用した結果のHTTP認証資格情報。

HTTP認証ヘッダーの値は、最初のスペースで分割されます。

最初の部分がscheme、2番目の部分がcredentialsです。

たとえば、HTTPベアラトークンスキームでは、クライアントは次のようなヘッダーを送信します

Authorization: Bearer deadbeef12346

この場合

  • schemeは値"Bearer"を持ちます
  • credentialsは値"deadbeef12346"を持ちます

scheme インスタンス属性

scheme

ヘッダー値から抽出されたHTTP認証スキーム。

credentials インスタンス属性

credentials

ヘッダー値から抽出されたHTTP認証資格情報。

fastapi.security.HTTPBasicCredentials

ベース: BaseModel

依存関係でHTTPBasicを使用した結果として与えられるHTTPベーシック認証資格情報。

HTTPベーシック認証のFastAPIドキュメントで詳細を読むことができます。

username インスタンス属性

username

HTTPベーシックユーザー名。

password インスタンス属性

password

HTTPベーシックパスワード。

OAuth2認証

fastapi.security.OAuth2

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

ベース: SecurityBase

これはOAuth2認証の基底クラスであり、そのインスタンスは依存関係として使用されます。他のすべての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

デフォルトでは、OAuth2認証に必要なHTTP Authorizationヘッダーが提供されていない場合、自動的にリクエストをキャンセルし、クライアントにエラーを送信します。

auto_errorFalseに設定されている場合、HTTP Authorizationヘッダーが利用できないとき、エラーを出す代わりに、依存関係の結果はNoneになります。

これは、オプションの認証を設定したい場合に便利です。

また、複数のオプションの方法(例えば、OAuth2またはクッキー)で認証を提供したい場合にも便利です。

タイプ: 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コードフローで取得されたベアラトークンを使用した認証のためのOAuth2フロー。そのインスタンスは依存関係として使用されます。

パラメータ 説明
tokenUrl

OAuth2トークンを取得するためのURL。

型: str

refreshUrl

トークンを更新して新しいトークンを取得するためのURL。

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

デフォルトでは、OAuth2認証に必要なHTTP Authorizationヘッダーが提供されていない場合、自動的にリクエストをキャンセルし、クライアントにエラーを送信します。

auto_errorFalseに設定されている場合、HTTP Authorizationヘッダーが利用できないとき、エラーを出す代わりに、依存関係の結果はNoneになります。

これは、オプションの認証を設定したい場合に便利です。

また、複数のオプションの方法(例えば、OAuth2またはクッキー)で認証を提供したい場合にも便利です。

タイプ: 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 インスタンス属性

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,
    refreshUrl=None,
)

ベース: OAuth2

パスワードで取得されたベアラトークンを使用した認証のためのOAuth2フロー。そのインスタンスは依存関係として使用されます。

パスワードとベアラを使用したシンプルなOAuth2に関するFastAPIドキュメントで詳細を読むことができます。

パラメータ 説明
tokenUrl

OAuth2トークンを取得するためのURL。これは、OAuth2PasswordRequestFormを依存関係として持つ パス操作 になります。

型: str

scheme_name

セキュリティスキーム名。

生成されたOpenAPIに含まれます(例: /docsで表示されます)。

型: Optional[str] デフォルト: None

scopes

この依存関係を使用する パス操作 で必要となるOAuth2スコープ。

タイプ: Optional[Dict[str, str]] デフォルト: None

description

セキュリティスキームの説明。

生成されたOpenAPIに含まれます(例: /docsで表示されます)。

型: Optional[str] デフォルト: None

auto_error

デフォルトでは、OAuth2認証に必要なHTTP Authorizationヘッダーが提供されていない場合、自動的にリクエストをキャンセルし、クライアントにエラーを送信します。

auto_errorFalseに設定されている場合、HTTP Authorizationヘッダーが利用できないとき、エラーを出す代わりに、依存関係の結果はNoneになります。

これは、オプションの認証を設定したい場合に便利です。

また、複数のオプションの方法(例えば、OAuth2またはクッキー)で認証を提供したい場合にも便利です。

タイプ: 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 インスタンス属性

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を持つ必要があると規定されています。

すべての初期化パラメータはリクエストから抽出されます。

パスワードとベアラを使用したシンプルなOAuth2に関するFastAPIドキュメントで詳細を読むことができます。

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の2つの部分を取得するためのカスタム内部ロジックを持つことができます。多くのアプリケーションは権限をグループ化して整理するためにこれを行いますが、ご自身のアプリケーションでも同様に行うことができます。ただし、それはアプリケーション固有であり、仕様の一部ではないことを知っておいてください。

パラメータ 説明
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仕様では、client_idclient_secret(存在する場合)をHTTPベーシック認証を使用して送信することを推奨しています。

型: Union[str, None] デフォルト: None

client_secret

client_password(とclient_id)がある場合、フォームフィールドの一部として送信できます。ただし、OAuth2仕様では、client_idclient_secret(存在する場合)をHTTPベーシック認証を使用して送信することを推奨しています。

型: 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 インスタンス属性

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仕様で要求されています(特に理由はないようですが)。一方、OAuth2PasswordRequestFormではgrant_typeはオプションです。

パスワードとベアラを使用したシンプルなOAuth2に関するFastAPIドキュメントで詳細を読むことができます。

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の2つの部分を取得するためのカスタム内部ロジックを持つことができます。多くのアプリケーションは権限をグループ化して整理するためにこれを行いますが、ご自身のアプリケーションでも同様に行うことができます。ただし、それはアプリケーション固有であり、仕様の一部ではないことを知っておいてください。

OAuth2仕様では、必須であり、固定文字列「password」である必要があるとされています。

この依存関係はこれに関して厳格です。寛容にしたい場合は、代わりにOAuth2PasswordRequestForm依存関係クラスを使用してください。

username: ユーザー名文字列。OAuth2仕様では、正確なフィールド名「username」が必要です。password: パスワード文字列。OAuth2仕様では、正確なフィールド名「password」が必要です。scope: オプションの文字列。スペースで区切られた複数のスコープ(それぞれ文字列)。例: "items:read items:write users:read profile openid" client_id: オプションの文字列。OAuth2では、client_idとclient_secret(存在する場合)をHTTP Basic認証(例: client_id:client_secret)を使用して送信することを推奨しています。client_secret: オプションの文字列。OAuth2では、client_idとclient_secret(存在する場合)をHTTP Basic認証(例: 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仕様では、client_idclient_secret(存在する場合)をHTTPベーシック認証を使用して送信することを推奨しています。

型: Union[str, None] デフォルト: None

client_secret

client_password(とclient_id)がある場合、フォームフィールドの一部として送信できます。ただし、OAuth2仕様では、client_idclient_secret(存在する場合)をHTTPベーシック認証を使用して送信することを推奨しています。

型: 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スコープを取得します。

これにより、複数の依存関係が、同じ パス操作 で使用されていても、異なるスコープを持つことができます。そして、これを使用すると、それらすべての依存関係で必要なすべてのスコープに単一の場所でアクセスできます。

OAuth2スコープに関するFastAPIドキュメントで詳細を読むことができます。

パラメータ 説明
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 インスタンス属性

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 Authorizationヘッダーが提供されていない場合、自動的にリクエストをキャンセルし、クライアントにエラーを送信します。

auto_errorFalseに設定されている場合、HTTP Authorizationヘッダーが利用できないとき、エラーを出す代わりに、依存関係の結果はNoneになります。

これは、オプションの認証を設定したい場合に便利です。

また、複数のオプションの方法(例えば、OpenID Connectまたはクッキー)で認証を提供したい場合にも便利です。

タイプ: 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