跳到内容

安全工具

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

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

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

你可以从 fastapi.security 中导入它们。

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

阅读更多相关信息,请参考 FastAPI 关于安全的文档

API 密钥安全方案

fastapi.security.APIKeyCookie

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

基类: APIKeyBase

使用 Cookie 的 API 密钥认证。

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

用法

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

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

示例

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

app = FastAPI()

cookie_scheme = APIKeyCookie(name="session")


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

Cookie 名称。

类型: str

scheme_name

安全方案名称。

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

类型: str | None 默认值: None

description

安全方案描述。

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

类型: str | None 默认值: None

auto_error

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

如果 auto_error 设置为 False,当 Cookie 不可用时,它不会报错,而是将依赖项结果设为 None

当你想要实现可选认证时,这很有用。

当你想要实现可以通过多种可选方式之一提供的认证(例如,通过 Cookie 或 HTTP Bearer 令牌)时,这也非常有用。

类型: bool 默认值: True

源代码位于 fastapi/security/api_key.py
def __init__(
    self,
    *,
    name: Annotated[str, Doc("Cookie name.")],
    scheme_name: Annotated[
        str | None,
        Doc(
            """
            Security scheme name.

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

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if the cookie is not provided, `APIKeyCookie` will
            automatically cancel the request and send the client an error.

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

            This is useful when you want to have optional authentication.

            It is also useful when you want to have authentication that can be
            provided in one of multiple optional ways (for example, in a cookie or
            in an HTTP Bearer token).
            """
        ),
    ] = True,
):
    super().__init__(
        location=APIKeyIn.cookie,
        name=name,
        scheme_name=scheme_name,
        description=description,
        auto_error=auto_error,
    )

model instance-attribute

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

scheme_name instance-attribute

scheme_name = scheme_name or __name__

auto_error instance-attribute

auto_error = auto_error

make_not_authenticated_error

make_not_authenticated_error()

WWW-Authenticate 标头并未针对 API 密钥认证进行标准化,但 HTTP 规范要求 401“未授权”错误必须包含 WWW-Authenticate 标头。

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

为此,该方法发送一个自定义的 APIKey 质询。

源代码位于 fastapi/security/api_key.py
def make_not_authenticated_error(self) -> HTTPException:
    """
    The WWW-Authenticate header is not standardized for API Key authentication but
    the HTTP specification requires that an error of 401 "Unauthorized" must
    include a WWW-Authenticate header.

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

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

check_api_key

check_api_key(api_key)
源代码位于 fastapi/security/api_key.py
def check_api_key(self, api_key: str | None) -> str | None:
    if not api_key:
        if self.auto_error:
            raise self.make_not_authenticated_error()
        return None
    return api_key

fastapi.security.APIKeyHeader

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

基类: APIKeyBase

使用 Header 的 API 密钥认证。

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

用法

创建一个实例对象,并将该对象用作 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

Header 名称。

类型: str

scheme_name

安全方案名称。

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

类型: str | None 默认值: None

description

安全方案描述。

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

类型: str | None 默认值: None

auto_error

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

如果 auto_error 设置为 False,当 Header 不可用时,它不会报错,而是将依赖项结果设为 None

当你想要实现可选认证时,这很有用。

当你想要实现可以通过多种可选方式之一提供的认证(例如,通过 Header 或 HTTP Bearer 令牌)时,这也非常有用。

类型: bool 默认值: True

源代码位于 fastapi/security/api_key.py
def __init__(
    self,
    *,
    name: Annotated[str, Doc("Header name.")],
    scheme_name: Annotated[
        str | None,
        Doc(
            """
            Security scheme name.

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

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if the header is not provided, `APIKeyHeader` will
            automatically cancel the request and send the client an error.

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

            This is useful when you want to have optional authentication.

            It is also useful when you want to have authentication that can be
            provided in one of multiple optional ways (for example, in a header or
            in an HTTP Bearer token).
            """
        ),
    ] = True,
):
    super().__init__(
        location=APIKeyIn.header,
        name=name,
        scheme_name=scheme_name,
        description=description,
        auto_error=auto_error,
    )

model instance-attribute

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

scheme_name instance-attribute

scheme_name = scheme_name or __name__

auto_error instance-attribute

auto_error = auto_error

make_not_authenticated_error

make_not_authenticated_error()

WWW-Authenticate 标头并未针对 API 密钥认证进行标准化,但 HTTP 规范要求 401“未授权”错误必须包含 WWW-Authenticate 标头。

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

为此,该方法发送一个自定义的 APIKey 质询。

源代码位于 fastapi/security/api_key.py
def make_not_authenticated_error(self) -> HTTPException:
    """
    The WWW-Authenticate header is not standardized for API Key authentication but
    the HTTP specification requires that an error of 401 "Unauthorized" must
    include a WWW-Authenticate header.

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

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

check_api_key

check_api_key(api_key)
源代码位于 fastapi/security/api_key.py
def check_api_key(self, api_key: str | None) -> str | None:
    if not api_key:
        if self.auto_error:
            raise self.make_not_authenticated_error()
        return None
    return api_key

fastapi.security.APIKeyQuery

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

基类: 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 中可见)。

类型: str | None 默认值: None

description

安全方案描述。

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

类型: str | None 默认值: None

auto_error

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

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

当你想要实现可选认证时,这很有用。

当你想要实现可以通过多种可选方式之一提供的认证(例如,通过查询参数或 HTTP Bearer 令牌)时,这也非常有用。

类型: bool 默认值: True

源代码位于 fastapi/security/api_key.py
def __init__(
    self,
    *,
    name: Annotated[
        str,
        Doc("Query parameter name."),
    ],
    scheme_name: Annotated[
        str | None,
        Doc(
            """
            Security scheme name.

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

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if the query parameter is not provided, `APIKeyQuery` will
            automatically cancel the request and send the client an error.

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

            This is useful when you want to have optional authentication.

            It is also useful when you want to have authentication that can be
            provided in one of multiple optional ways (for example, in a query
            parameter or in an HTTP Bearer token).
            """
        ),
    ] = True,
):
    super().__init__(
        location=APIKeyIn.query,
        name=name,
        scheme_name=scheme_name,
        description=description,
        auto_error=auto_error,
    )

model instance-attribute

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

scheme_name instance-attribute

scheme_name = scheme_name or __name__

auto_error instance-attribute

auto_error = auto_error

make_not_authenticated_error

make_not_authenticated_error()

WWW-Authenticate 标头并未针对 API 密钥认证进行标准化,但 HTTP 规范要求 401“未授权”错误必须包含 WWW-Authenticate 标头。

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

为此,该方法发送一个自定义的 APIKey 质询。

源代码位于 fastapi/security/api_key.py
def make_not_authenticated_error(self) -> HTTPException:
    """
    The WWW-Authenticate header is not standardized for API Key authentication but
    the HTTP specification requires that an error of 401 "Unauthorized" must
    include a WWW-Authenticate header.

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

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

check_api_key

check_api_key(api_key)
源代码位于 fastapi/security/api_key.py
def check_api_key(self, api_key: str | None) -> str | None:
    if not api_key:
        if self.auto_error:
            raise self.make_not_authenticated_error()
        return None
    return api_key

HTTP 认证方案

fastapi.security.HTTPBasic

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

基类: HTTPBase

HTTP 基本认证。

参考: https://datatracker.ietf.org/doc/html/rfc7617

用法

创建一个实例对象,并将该对象用作 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 中可见)。

类型: str | None 默认值: None

realm

HTTP 基本认证域。

类型: str | None 默认值: None

description

安全方案描述。

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

类型: str | None 默认值: None

auto_error

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

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

当你想要实现可选认证时,这很有用。

当你想要实现可以通过多种可选方式之一提供的认证(例如,通过 HTTP 基本认证或 HTTP Bearer 令牌)时,这也非常有用。

类型: bool 默认值: True

源代码位于 fastapi/security/http.py
def __init__(
    self,
    *,
    scheme_name: Annotated[
        str | None,
        Doc(
            """
            Security scheme name.

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

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if the HTTP Basic authentication is not provided (a
            header), `HTTPBasic` will automatically cancel the request and send the
            client an error.

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

            This is useful when you want to have optional authentication.

            It is also useful when you want to have authentication that can be
            provided in one of multiple optional ways (for example, in HTTP Basic
            authentication or in an HTTP Bearer token).
            """
        ),
    ] = True,
):
    self.model = HTTPBaseModel(scheme="basic", description=description)
    self.scheme_name = scheme_name or self.__class__.__name__
    self.realm = realm
    self.auto_error = auto_error

model instance-attribute

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

scheme_name instance-attribute

scheme_name = scheme_name or __name__

realm instance-attribute

realm = realm

auto_error instance-attribute

auto_error = auto_error

make_not_authenticated_error

make_not_authenticated_error()
源代码位于 fastapi/security/http.py
def make_not_authenticated_error(self) -> HTTPException:
    return HTTPException(
        status_code=HTTP_401_UNAUTHORIZED,
        detail="Not authenticated",
        headers=self.make_authenticate_headers(),
    )

make_authenticate_headers

make_authenticate_headers()
源代码位于 fastapi/security/http.py
def make_authenticate_headers(self) -> dict[str, str]:
    if self.realm:
        return {"WWW-Authenticate": f'Basic realm="{self.realm}"'}
    return {"WWW-Authenticate": "Basic"}

fastapi.security.HTTPBearer

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

基类: HTTPBase

HTTP Bearer 令牌认证。

用法

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

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

示例

from typing import Annotated

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

app = FastAPI()

security = HTTPBearer()


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

Bearer 令牌格式。

类型: str | None 默认值: None

scheme_name

安全方案名称。

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

类型: str | None 默认值: None

description

安全方案描述。

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

类型: str | None 默认值: None

auto_error

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

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

当你想要实现可选认证时,这很有用。

当你想要实现可以通过多种可选方式之一提供的认证(例如,通过 HTTP Bearer 令牌或 Cookie)时,这也非常有用。

类型: bool 默认值: True

源代码位于 fastapi/security/http.py
def __init__(
    self,
    *,
    bearerFormat: Annotated[str | None, Doc("Bearer token format.")] = None,
    scheme_name: Annotated[
        str | None,
        Doc(
            """
            Security scheme name.

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

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if the HTTP Bearer token is not provided (in an
            `Authorization` header), `HTTPBearer` will automatically cancel the
            request and send the client an error.

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

            This is useful when you want to have optional authentication.

            It is also useful when you want to have authentication that can be
            provided in one of multiple optional ways (for example, in an HTTP
            Bearer token or in a cookie).
            """
        ),
    ] = True,
):
    self.model = HTTPBearerModel(bearerFormat=bearerFormat, description=description)
    self.scheme_name = scheme_name or self.__class__.__name__
    self.auto_error = auto_error

model instance-attribute

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

scheme_name instance-attribute

scheme_name = scheme_name or __name__

auto_error instance-attribute

auto_error = auto_error

make_authenticate_headers

make_authenticate_headers()
源代码位于 fastapi/security/http.py
def make_authenticate_headers(self) -> dict[str, str]:
    return {"WWW-Authenticate": f"{self.model.scheme.title()}"}

make_not_authenticated_error

make_not_authenticated_error()
源代码位于 fastapi/security/http.py
def make_not_authenticated_error(self) -> HTTPException:
    return HTTPException(
        status_code=HTTP_401_UNAUTHORIZED,
        detail="Not authenticated",
        headers=self.make_authenticate_headers(),
    )

fastapi.security.HTTPDigest

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

基类: HTTPBase

HTTP Digest 认证。

警告: 这仅仅是一个为了在 FastAPI 中连接 OpenAPI 组件的存根,它并没有实现完整的 Digest 方案,你需要继承它并在你的代码中实现它。

参考: https://datatracker.ietf.org/doc/html/rfc7616

用法

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

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

示例

from typing import Annotated

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

app = FastAPI()

security = HTTPDigest()


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

安全方案名称。

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

类型: str | None 默认值: None

description

安全方案描述。

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

类型: str | None 默认值: None

auto_error

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

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

当你想要实现可选认证时,这很有用。

当你想要实现可以通过多种可选方式之一提供的认证(例如,通过 HTTP Digest 或 Cookie)时,这也非常有用。

类型: bool 默认值: True

源代码位于 fastapi/security/http.py
def __init__(
    self,
    *,
    scheme_name: Annotated[
        str | None,
        Doc(
            """
            Security scheme name.

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

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if the HTTP Digest is not provided, `HTTPDigest` will
            automatically cancel the request and send the client an error.

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

            This is useful when you want to have optional authentication.

            It is also useful when you want to have authentication that can be
            provided in one of multiple optional ways (for example, in HTTP
            Digest or in a cookie).
            """
        ),
    ] = True,
):
    self.model = HTTPBaseModel(scheme="digest", description=description)
    self.scheme_name = scheme_name or self.__class__.__name__
    self.auto_error = auto_error

model instance-attribute

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

scheme_name instance-attribute

scheme_name = scheme_name or __name__

auto_error instance-attribute

auto_error = auto_error

make_authenticate_headers

make_authenticate_headers()
源代码位于 fastapi/security/http.py
def make_authenticate_headers(self) -> dict[str, str]:
    return {"WWW-Authenticate": f"{self.model.scheme.title()}"}

make_not_authenticated_error

make_not_authenticated_error()
源代码位于 fastapi/security/http.py
def make_not_authenticated_error(self) -> HTTPException:
    return HTTPException(
        status_code=HTTP_401_UNAUTHORIZED,
        detail="Not authenticated",
        headers=self.make_authenticate_headers(),
    )

HTTP 凭据

fastapi.security.HTTPAuthorizationCredentials

基类: BaseModel

在依赖项中使用 HTTPBearerHTTPDigest 结果中的 HTTP 授权凭据。

HTTP 授权标头的值按第一个空格进行分割。

第一部分是 scheme(方案),第二部分是 credentials(凭据)。

例如,在 HTTP Bearer 令牌方案中,客户端将发送类似如下的标头:

Authorization: Bearer deadbeef12346

在这种情况下:

  • scheme 的值将为 "Bearer"
  • credentials 的值将为 "deadbeef12346"

scheme instance-attribute

scheme

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

credentials instance-attribute

credentials

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

fastapi.security.HTTPBasicCredentials

基类: BaseModel

在依赖项中使用 HTTPBasic 时给出的 HTTP 基本认证凭据。

阅读更多相关信息,请参考 FastAPI 关于 HTTP 基本认证的文档

username instance-attribute

username

HTTP 基本认证的用户名。

password instance-attribute

password

HTTP 基本认证的密码。

OAuth2 认证

fastapi.security.OAuth2

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

基类: SecurityBase

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

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

阅读更多相关信息,请参考 FastAPI 关于安全的文档

参数 描述
flows

OAuth2 流程的字典。

类型: OAuthFlows | dict[str, dict[str, Any]] 默认值: OAuthFlows()

scheme_name

安全方案名称。

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

类型: str | None 默认值: None

description

安全方案描述。

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

类型: str | None 默认值: None

auto_error

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

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

当你想要实现可选认证时,这很有用。

当你想要实现可以通过多种可选方式之一提供的认证(例如,通过 OAuth2 或 Cookie)时,这也非常有用。

类型: bool 默认值: True

源代码位于 fastapi/security/oauth2.py
def __init__(
    self,
    *,
    flows: Annotated[
        OAuthFlowsModel | dict[str, dict[str, Any]],
        Doc(
            """
            The dictionary of OAuth2 flows.
            """
        ),
    ] = OAuthFlowsModel(),
    scheme_name: Annotated[
        str | None,
        Doc(
            """
            Security scheme name.

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

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if no HTTP Authorization header is provided, required for
            OAuth2 authentication, it will automatically cancel the request and
            send the client an error.

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

            This is useful when you want to have optional authentication.

            It is also useful when you want to have authentication that can be
            provided in one of multiple optional ways (for example, with OAuth2
            or in a cookie).
            """
        ),
    ] = True,
):
    self.model = OAuth2Model(
        flows=cast(OAuthFlowsModel, flows), description=description
    )
    self.scheme_name = scheme_name or self.__class__.__name__
    self.auto_error = auto_error

model instance-attribute

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

scheme_name instance-attribute

scheme_name = scheme_name or __name__

auto_error instance-attribute

auto_error = auto_error

make_not_authenticated_error

make_not_authenticated_error()

OAuth 2 规范并未定义应该使用哪种质询,因为 Bearer 令牌并不是认证的唯一选择。

但声明任何其他认证质询都是特定于应用程序的,因为规范中并未定义。

出于实际原因,此方法默认使用 Bearer 质询,因为它可能是最常见的一种。

如果你正在实现非 FastAPI 提供(基于 Bearer 令牌)的 OAuth2 认证方案,你可能需要重写此方法。

参考: https://datatracker.ietf.org/doc/html/rfc6749

源代码位于 fastapi/security/oauth2.py
def make_not_authenticated_error(self) -> HTTPException:
    """
    The OAuth 2 specification doesn't define the challenge that should be used,
    because a `Bearer` token is not really the only option to authenticate.

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

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

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

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

fastapi.security.OAuth2AuthorizationCodeBearer

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

基类: OAuth2

用于使用 OAuth2 代码流程获取的 Bearer 令牌进行认证的 OAuth2 流程。它的一个实例将用作依赖项。

参数 描述
tokenUrl

获取 OAuth2 令牌的 URL。

类型: str

refreshUrl

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

类型: str | None 默认值: None

scheme_name

安全方案名称。

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

类型: str | None 默认值: None

scopes

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

类型: dict[str, str] | None 默认值: None

description

安全方案描述。

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

类型: str | None 默认值: None

auto_error

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

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

当你想要实现可选认证时,这很有用。

当你想要实现可以通过多种可选方式之一提供的认证(例如,通过 OAuth2 或 Cookie)时,这也非常有用。

类型: bool 默认值: True

源代码位于 fastapi/security/oauth2.py
def __init__(
    self,
    authorizationUrl: str,
    tokenUrl: Annotated[
        str,
        Doc(
            """
            The URL to obtain the OAuth2 token.
            """
        ),
    ],
    refreshUrl: Annotated[
        str | None,
        Doc(
            """
            The URL to refresh the token and obtain a new one.
            """
        ),
    ] = None,
    scheme_name: Annotated[
        str | None,
        Doc(
            """
            Security scheme name.

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

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if no HTTP Authorization header is provided, required for
            OAuth2 authentication, it will automatically cancel the request and
            send the client an error.

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

            This is useful when you want to have optional authentication.

            It is also useful when you want to have authentication that can be
            provided in one of multiple optional ways (for example, with OAuth2
            or in a cookie).
            """
        ),
    ] = True,
):
    if not scopes:
        scopes = {}
    flows = OAuthFlowsModel(
        authorizationCode=cast(
            Any,
            {
                "authorizationUrl": authorizationUrl,
                "tokenUrl": tokenUrl,
                "refreshUrl": refreshUrl,
                "scopes": scopes,
            },
        )
    )
    super().__init__(
        flows=flows,
        scheme_name=scheme_name,
        description=description,
        auto_error=auto_error,
    )

model instance-attribute

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

scheme_name instance-attribute

scheme_name = scheme_name or __name__

auto_error instance-attribute

auto_error = auto_error

make_not_authenticated_error

make_not_authenticated_error()

OAuth 2 规范并未定义应该使用哪种质询,因为 Bearer 令牌并不是认证的唯一选择。

但声明任何其他认证质询都是特定于应用程序的,因为规范中并未定义。

出于实际原因,此方法默认使用 Bearer 质询,因为它可能是最常见的一种。

如果你正在实现非 FastAPI 提供(基于 Bearer 令牌)的 OAuth2 认证方案,你可能需要重写此方法。

参考: https://datatracker.ietf.org/doc/html/rfc6749

源代码位于 fastapi/security/oauth2.py
def make_not_authenticated_error(self) -> HTTPException:
    """
    The OAuth 2 specification doesn't define the challenge that should be used,
    because a `Bearer` token is not really the only option to authenticate.

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

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

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

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

fastapi.security.OAuth2PasswordBearer

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

基类: OAuth2

用于使用密码获取的 Bearer 令牌进行认证的 OAuth2 流程。它的一个实例将用作依赖项。

阅读更多相关信息,请参考 FastAPI 关于密码和 Bearer 的简单 OAuth2 文档

参数 描述
tokenUrl

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

阅读更多相关信息,请参考 FastAPI 关于密码和 Bearer 的简单 OAuth2 文档

类型: str

scheme_name

安全方案名称。

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

类型: str | None 默认值: None

scopes

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

阅读更多相关信息,请参考 FastAPI 关于密码和 Bearer 的简单 OAuth2 文档

类型: dict[str, str] | None 默认值: None

description

安全方案描述。

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

类型: str | None 默认值: None

auto_error

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

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

当你想要实现可选认证时,这很有用。

当你想要实现可以通过多种可选方式之一提供的认证(例如,通过 OAuth2 或 Cookie)时,这也非常有用。

类型: bool 默认值: True

refreshUrl

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

类型: str | None 默认值: None

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

            Read more about it in the
            [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.org.cn/tutorial/security/simple-oauth2/).
            """
        ),
    ],
    scheme_name: Annotated[
        str | None,
        Doc(
            """
            Security scheme name.

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

            Read more about it in the
            [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.org.cn/tutorial/security/simple-oauth2/).
            """
        ),
    ] = None,
    description: Annotated[
        str | None,
        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[
        str | None,
        Doc(
            """
            The URL to refresh the token and obtain a new one.
            """
        ),
    ] = None,
):
    if not scopes:
        scopes = {}
    flows = OAuthFlowsModel(
        password=cast(
            Any,
            {
                "tokenUrl": tokenUrl,
                "refreshUrl": refreshUrl,
                "scopes": scopes,
            },
        )
    )
    super().__init__(
        flows=flows,
        scheme_name=scheme_name,
        description=description,
        auto_error=auto_error,
    )

model instance-attribute

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

scheme_name instance-attribute

scheme_name = scheme_name or __name__

auto_error instance-attribute

auto_error = auto_error

make_not_authenticated_error

make_not_authenticated_error()

OAuth 2 规范并未定义应该使用哪种质询,因为 Bearer 令牌并不是认证的唯一选择。

但声明任何其他认证质询都是特定于应用程序的,因为规范中并未定义。

出于实际原因,此方法默认使用 Bearer 质询,因为它可能是最常见的一种。

如果你正在实现非 FastAPI 提供(基于 Bearer 令牌)的 OAuth2 认证方案,你可能需要重写此方法。

参考: https://datatracker.ietf.org/doc/html/rfc6749

源代码位于 fastapi/security/oauth2.py
def make_not_authenticated_error(self) -> HTTPException:
    """
    The OAuth 2 specification doesn't define the challenge that should be used,
    because a `Bearer` token is not really the only option to authenticate.

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

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

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

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

OAuth2 密码表单

fastapi.security.OAuth2PasswordRequestForm

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

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

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

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

阅读更多相关信息,请参考 FastAPI 关于密码和 Bearer 的简单 OAuth2 文档

示例

from typing import Annotated

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

app = FastAPI()


@app.post("/login")
def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):
    data = {}
    data["scopes"] = []
    for scope in form_data.scopes:
        data["scopes"].append(scope)
    if form_data.client_id:
        data["client_id"] = form_data.client_id
    if form_data.client_secret:
        data["client_secret"] = form_data.client_secret
    return data

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

参数 描述
grant_type

OAuth2 规范称它是必需的,并且必须是固定的字符串“password”。尽管如此,此依赖项类是宽容的,允许不传递它。如果你想强制执行,请改用 OAuth2PasswordRequestFormStrict 依赖项。

阅读更多相关信息,请参考 FastAPI 关于密码和 Bearer 的简单 OAuth2 文档

类型: str | None 默认值: None

username

username 字符串。OAuth2 规范要求完全使用 username 字段名称。

阅读更多相关信息,请参考 FastAPI 关于密码和 Bearer 的简单 OAuth2 文档

类型: str

password

password 字符串。OAuth2 规范要求完全使用 password 字段名称。

阅读更多相关信息,请参考 FastAPI 关于密码和 Bearer 的简单 OAuth2 文档

类型: str

scope

一个实际上包含几个以空格分隔的范围的单个字符串。每个范围也是一个字符串。

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

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

将代表以下范围:

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

阅读更多相关信息,请参考 FastAPI 关于密码和 Bearer 的简单 OAuth2 文档

类型: str 默认值: ''

client_id

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

类型: str | None 默认值: None

client_secret

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

类型: str | None 默认值: None

源代码位于 fastapi/security/oauth2.py
def __init__(
    self,
    *,
    grant_type: Annotated[
        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.

            Read more about it in the
            [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.org.cn/tutorial/security/simple-oauth2/).
            """
        ),
    ] = None,
    username: Annotated[
        str,
        Form(),
        Doc(
            """
            `username` string. The OAuth2 spec requires the exact field name
            `username`.

            Read more about it in the
            [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.org.cn/tutorial/security/simple-oauth2/).
            """
        ),
    ],
    password: Annotated[
        str,
        Form(json_schema_extra={"format": "password"}),
        Doc(
            """
            `password` string. The OAuth2 spec requires the exact field name
            `password`.

            Read more about it in the
            [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.org.cn/tutorial/security/simple-oauth2/).
            """
        ),
    ],
    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`

            Read more about it in the
            [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.org.cn/tutorial/security/simple-oauth2/).
            """
        ),
    ] = "",
    client_id: Annotated[
        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[
        str | None,
        Form(json_schema_extra={"format": "password"}),
        Doc(
            """
            If there's a `client_secret` (and a `client_id`), they can be sent
            as part of the form fields. But the OAuth2 specification recommends
            sending the `client_id` and `client_secret` (if any) using HTTP Basic
            auth.
            """
        ),
    ] = None,
):
    self.grant_type = grant_type
    self.username = username
    self.password = password
    self.scopes = scope.split()
    self.client_id = client_id
    self.client_secret = client_secret

grant_type instance-attribute

grant_type = grant_type

username instance-attribute

username = username

password instance-attribute

password = password

scopes instance-attribute

scopes = split()

client_id instance-attribute

client_id = client_id

client_secret instance-attribute

client_secret = client_secret

fastapi.security.OAuth2PasswordRequestFormStrict

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

基类: OAuth2PasswordRequestForm

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

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

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

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

阅读更多相关信息,请参考 FastAPI 关于密码和 Bearer 的简单 OAuth2 文档

示例

from typing import Annotated

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

app = FastAPI()


@app.post("/login")
def login(form_data: Annotated[OAuth2PasswordRequestFormStrict, Depends()]):
    data = {}
    data["scopes"] = []
    for scope in form_data.scopes:
        data["scopes"].append(scope)
    if form_data.client_id:
        data["client_id"] = form_data.client_id
    if form_data.client_secret:
        data["client_secret"] = form_data.client_secret
    return data

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

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

此依赖项对此非常严格。如果你想更加宽容,请改用 OAuth2PasswordRequestForm 依赖项类。

username: 用户名字符串。OAuth2 规范要求完全使用 "username" 字段名称。password: 密码字符串。OAuth2 规范要求完全使用 "password" 字段名称。scope: 可选字符串。几个以空格分隔的范围(每个均为字符串)。例如 "items:read items:write users:read profile openid" client_id: 可选字符串。OAuth2 建议使用 HTTP 基本认证发送 client_id 和 client_secret(如果有),格式为:client_id:client_secret client_secret: 可选字符串。OAuth2 建议使用 HTTP 基本认证发送 client_id 和 client_secret(如果有),格式为:client_id:client_secret

参数 描述
grant_type

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

阅读更多相关信息,请参考 FastAPI 关于密码和 Bearer 的简单 OAuth2 文档

类型: str

username

username 字符串。OAuth2 规范要求完全使用 username 字段名称。

阅读更多相关信息,请参考 FastAPI 关于密码和 Bearer 的简单 OAuth2 文档

类型: str

password

password 字符串。OAuth2 规范要求完全使用 password 字段名称。

阅读更多相关信息,请参考 FastAPI 关于密码和 Bearer 的简单 OAuth2 文档

类型: str

scope

一个实际上包含几个以空格分隔的范围的单个字符串。每个范围也是一个字符串。

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

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

将代表以下范围:

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

阅读更多相关信息,请参考 FastAPI 关于密码和 Bearer 的简单 OAuth2 文档

类型: str 默认值: ''

client_id

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

类型: str | None 默认值: None

client_secret

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

类型: str | None 默认值: None

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

            Read more about it in the
            [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.org.cn/tutorial/security/simple-oauth2/).
            """
        ),
    ],
    username: Annotated[
        str,
        Form(),
        Doc(
            """
            `username` string. The OAuth2 spec requires the exact field name
            `username`.

            Read more about it in the
            [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.org.cn/tutorial/security/simple-oauth2/).
            """
        ),
    ],
    password: Annotated[
        str,
        Form(),
        Doc(
            """
            `password` string. The OAuth2 spec requires the exact field name
            `password`.

            Read more about it in the
            [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.org.cn/tutorial/security/simple-oauth2/).
            """
        ),
    ],
    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`

            Read more about it in the
            [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.org.cn/tutorial/security/simple-oauth2/).
            """
        ),
    ] = "",
    client_id: Annotated[
        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[
        str | None,
        Form(),
        Doc(
            """
            If there's a `client_secret` (and a `client_id`), they can be sent
            as part of the form fields. But the OAuth2 specification recommends
            sending the `client_id` and `client_secret` (if any) using HTTP Basic
            auth.
            """
        ),
    ] = None,
):
    super().__init__(
        grant_type=grant_type,
        username=username,
        password=password,
        scope=scope,
        client_id=client_id,
        client_secret=client_secret,
    )

grant_type instance-attribute

grant_type = grant_type

username instance-attribute

username = username

password instance-attribute

password = password

scopes instance-attribute

scopes = split()

client_id instance-attribute

client_id = client_id

client_secret instance-attribute

client_secret = client_secret

依赖项中的 OAuth2 安全范围

fastapi.security.SecurityScopes

SecurityScopes(scopes=None)

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

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

阅读更多相关信息,请参考 FastAPI 关于 OAuth2 范围的文档

参数 描述
scopes

这将由 FastAPI 填充。

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

源代码位于 fastapi/security/oauth2.py
def __init__(
    self,
    scopes: Annotated[
        list[str] | None,
        Doc(
            """
            This will be filled by FastAPI.
            """
        ),
    ] = None,
):
    self.scopes: Annotated[
        list[str],
        Doc(
            """
            The list of all the scopes required by dependencies.
            """
        ),
    ] = scopes or []
    self.scope_str: Annotated[
        str,
        Doc(
            """
            All the scopes required by all the dependencies in a single string
            separated by spaces, as defined in the OAuth2 specification.
            """
        ),
    ] = " ".join(self.scopes)

scopes instance-attribute

scopes = scopes or []

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

scope_str instance-attribute

scope_str = join(scopes)

按照 OAuth2 规范的定义,所有依赖项所需的所有范围以单个以空格分隔的字符串形式存在。

OpenID Connect

fastapi.security.OpenIdConnect

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

基类: SecurityBase

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

警告: 这仅仅是一个为了在 FastAPI 中连接 OpenAPI 组件的存根,它并没有实现完整的 OpenIdConnect 方案,例如,它不使用 OpenIDConnect URL。你需要继承它并在你的代码中实现它。

参数 描述
openIdConnectUrl

OpenID Connect URL。

类型: str

scheme_name

安全方案名称。

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

类型: str | None 默认值: None

description

安全方案描述。

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

类型: str | None 默认值: None

auto_error

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

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

当你想要实现可选认证时,这很有用。

当你想要实现可以通过多种可选方式之一提供的认证(例如,通过 OpenID Connect 或 Cookie)时,这也非常有用。

类型: bool 默认值: True

源代码位于 fastapi/security/open_id_connect_url.py
def __init__(
    self,
    *,
    openIdConnectUrl: Annotated[
        str,
        Doc(
            """
        The OpenID Connect URL.
        """
        ),
    ],
    scheme_name: Annotated[
        str | None,
        Doc(
            """
            Security scheme name.

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

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if no HTTP Authorization header is provided, required for
            OpenID Connect authentication, it will automatically cancel the request
            and send the client an error.

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

            This is useful when you want to have optional authentication.

            It is also useful when you want to have authentication that can be
            provided in one of multiple optional ways (for example, with OpenID
            Connect or in a cookie).
            """
        ),
    ] = True,
):
    self.model = OpenIdConnectModel(
        openIdConnectUrl=openIdConnectUrl, description=description
    )
    self.scheme_name = scheme_name or self.__class__.__name__
    self.auto_error = auto_error

model instance-attribute

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

scheme_name instance-attribute

scheme_name = scheme_name or __name__

auto_error instance-attribute

auto_error = auto_error

make_not_authenticated_error

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