Saltar al contenido

Herramientas de Seguridad

Cuando necesitas declarar dependencias con scopes de OAuth2 usas Security().

Pero todavía necesitas definir cuál es la dependencia, el callable que pasas como parámetro a Depends() o Security().

Hay múltiples herramientas que puedes usar para crear esas dependencias, y se integran en OpenAPI para que se muestren en la UI de documentación automática, pueden ser usadas por clientes y SDKs generados automáticamente, etc.

Puedes importarlas desde fastapi.security:

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

Lee más sobre ellas en la documentación de FastAPI sobre Seguridad.

Esquemas de Seguridad de API Key

fastapi.security.APIKeyCookie

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

Bases: APIKeyBase

Autenticación de API key usando una cookie.

Esto define el nombre de la cookie que debería ser proporcionada en la petición con la API key y lo integra en la documentación de OpenAPI. Extrae el valor de la key enviado en la cookie automáticamente y lo proporciona como el resultado de la dependencia. Pero no define cómo establecer esa cookie.

Uso

Crea un objeto instancia y usa ese objeto como la dependencia en Depends().

El resultado de la dependencia será un string que contiene el valor de la key.

Ejemplo

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}
PARÁMETRO DESCRIPCIÓN
name

Nombre de la cookie.

TYPE: str

scheme_name

Nombre del esquema de seguridad.

Será incluido en el OpenAPI generado (ej. visible en /docs).

TYPE: str | None DEFAULT: None

description

Descripción del esquema de seguridad.

Será incluido en el OpenAPI generado (ej. visible en /docs).

TYPE: str | None DEFAULT: None

auto_error

Por defecto, si la cookie no se proporciona, APIKeyCookie cancelará automáticamente la petición y enviará al cliente un error.

Si auto_error está establecido a False, cuando la cookie no está disponible, en lugar de dar error, el resultado de la dependencia será None.

Esto es útil cuando quieres tener autenticación opcional.

También es útil cuando quieres tener autenticación que puede ser proporcionada de una de múltiples formas opcionales (por ejemplo, en una cookie o en un token HTTP Bearer).

TYPE: bool DEFAULT: True

Código fuente en 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()

El header WWW-Authenticate no está estandarizado para autenticación de API Key pero la especificación HTTP requiere que un error 401 "Unauthorized" debe incluir un header WWW-Authenticate.

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

Para esto, este método envía un challenge personalizado APIKey.

Código fuente en 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)
Código fuente en 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
)

Bases: APIKeyBase

Autenticación de API key usando un header.

Esto define el nombre del header que debería ser proporcionado en la petición con la API key y lo integra en la documentación de OpenAPI. Extrae el valor de la key enviado en el header automáticamente y lo proporciona como el resultado de la dependencia. Pero no define cómo enviar esa key al cliente.

Uso

Crea un objeto instancia y usa ese objeto como la dependencia en Depends().

El resultado de la dependencia será un string que contiene el valor de la key.

Ejemplo

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}
PARÁMETRO DESCRIPCIÓN
name

Nombre del header.

TYPE: str

scheme_name

Nombre del esquema de seguridad.

Será incluido en el OpenAPI generado (ej. visible en /docs).

TYPE: str | None DEFAULT: None

description

Descripción del esquema de seguridad.

Será incluido en el OpenAPI generado (ej. visible en /docs).

TYPE: str | None DEFAULT: None

auto_error

Por defecto, si el header no se proporciona, APIKeyHeader cancelará automáticamente la petición y enviará al cliente un error.

Si auto_error está establecido a False, cuando el header no está disponible, en lugar de dar error, el resultado de la dependencia será None.

Esto es útil cuando quieres tener autenticación opcional.

También es útil cuando quieres tener autenticación que puede ser proporcionada de una de múltiples formas opcionales (por ejemplo, en un header o en un token HTTP Bearer).

TYPE: bool DEFAULT: True

Código fuente en 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()

El header WWW-Authenticate no está estandarizado para autenticación de API Key pero la especificación HTTP requiere que un error 401 "Unauthorized" debe incluir un header WWW-Authenticate.

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

Para esto, este método envía un challenge personalizado APIKey.

Código fuente en 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)
Código fuente en 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
)

Bases: APIKeyBase

Autenticación de API key usando un parámetro query.

Esto define el nombre del parámetro query que debería ser proporcionado en la petición con la API key y lo integra en la documentación de OpenAPI. Extrae el valor de la key enviado en el parámetro query automáticamente y lo proporciona como el resultado de la dependencia. Pero no define cómo enviar esa API key al cliente.

Uso

Crea un objeto instancia y usa ese objeto como la dependencia en Depends().

El resultado de la dependencia será un string que contiene el valor de la key.

Ejemplo

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}
PARÁMETRO DESCRIPCIÓN
name

Nombre del parámetro query.

TYPE: str

scheme_name

Nombre del esquema de seguridad.

Será incluido en el OpenAPI generado (ej. visible en /docs).

TYPE: str | None DEFAULT: None

description

Descripción del esquema de seguridad.

Será incluido en el OpenAPI generado (ej. visible en /docs).

TYPE: str | None DEFAULT: None

auto_error

Por defecto, si el parámetro query no se proporciona, APIKeyQuery cancelará automáticamente la petición y enviará al cliente un error.

Si auto_error está establecido a False, cuando el parámetro query no está available, en lugar de dar error, el resultado de la dependencia será None.

Esto es útil cuando quieres tener autenticación opcional.

También es útil cuando quieres tener autenticación que puede ser proporcionada de una de múltiples formas opcionales (por ejemplo, en un parámetro query o en un token HTTP Bearer).

TYPE: bool DEFAULT: True

Código fuente en 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()

El header WWW-Authenticate no está estandarizado para autenticación de API Key pero la especificación HTTP requiere que un error 401 "Unauthorized" debe incluir un header WWW-Authenticate.

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

Para esto, este método envía un challenge personalizado APIKey.

Código fuente en 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)
Código fuente en 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

Esquemas de Autenticación HTTP

fastapi.security.HTTPBasic

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

Bases: HTTPBase

Autenticación HTTP Basic.

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

Uso

Crea un objeto instancia y usa ese objeto como la dependencia en Depends().

El resultado de la dependencia será un objeto HTTPBasicCredentials que contiene el username y el password.

Lee más sobre esto en la documentación de FastAPI para HTTP Basic Auth.

Ejemplo

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}
PARÁMETRO DESCRIPCIÓN
scheme_name

Nombre del esquema de seguridad.

Será incluido en el OpenAPI generado (ej. visible en /docs).

TYPE: str | None DEFAULT: None

realm

Realm de autenticación HTTP Basic.

TYPE: str | None DEFAULT: None

description

Descripción del esquema de seguridad.

Será incluido en el OpenAPI generado (ej. visible en /docs).

TYPE: str | None DEFAULT: None

auto_error

Por defecto, si la autenticación HTTP Basic no se proporciona (un header), HTTPBasic cancelará automáticamente la petición y enviará al cliente un error.

Si auto_error está establecido a False, cuando la autenticación HTTP Basic no está disponible, en lugar de dar error, el resultado de la dependencia será None.

Esto es útil cuando quieres tener autenticación opcional.

También es útil cuando quieres tener autenticación que puede ser proporcionada de una de múltiples formas opcionales (por ejemplo, en autenticación HTTP Basic o en un token HTTP Bearer).

TYPE: bool DEFAULT: True

Código fuente en 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()
Código fuente en 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()
Código fuente en 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
)

Bases: HTTPBase

Autenticación de token HTTP Bearer.

Uso

Crea un objeto instancia y usa ese objeto como la dependencia en Depends().

El resultado de la dependencia será un objeto HTTPAuthorizationCredentials que contiene el scheme y las credentials.

Ejemplo

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}
PARÁMETRO DESCRIPCIÓN
bearerFormat

Formato del token Bearer.

TYPE: str | None DEFAULT: None

scheme_name

Nombre del esquema de seguridad.

Será incluido en el OpenAPI generado (ej. visible en /docs).

TYPE: str | None DEFAULT: None

description

Descripción del esquema de seguridad.

Será incluido en el OpenAPI generado (ej. visible en /docs).

TYPE: str | None DEFAULT: None

auto_error

Por defecto, si el token HTTP Bearer no se proporciona (en un header Authorization), HTTPBearer cancelará automáticamente la petición y enviará al cliente un error.

Si auto_error está establecido a False, cuando el token HTTP Bearer no está disponible, en lugar de dar error, el resultado de la dependencia será None.

Esto es útil cuando quieres tener autenticación opcional.

También es útil cuando quieres tener autenticación que puede ser proporcionada de una de múltiples formas opcionales (por ejemplo, en un token HTTP Bearer o en una cookie).

TYPE: bool DEFAULT: True

Código fuente en 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()
Código fuente en 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()
Código fuente en 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
)

Bases: HTTPBase

Autenticación HTTP Digest.

Aviso: esto es solo un stub para conectar los componentes con OpenAPI en FastAPI, pero no implementa el esquema Digest completo, necesitarías crear una subclase implementarlo en tu código.

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

Uso

Crea un objeto instancia y usa ese objeto como la dependencia en Depends().

El resultado de la dependencia será un objeto HTTPAuthorizationCredentials que contiene el scheme y las credentials.

Ejemplo

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}
PARÁMETRO DESCRIPCIÓN
scheme_name

Nombre del esquema de seguridad.

Será incluido en el OpenAPI generado (ej. visible en /docs).

TYPE: str | None DEFAULT: None

description

Descripción del esquema de seguridad.

Será incluido en el OpenAPI generado (ej. visible en /docs).

TYPE: str | None DEFAULT: None

auto_error

Por defecto, si el HTTP Digest no se proporciona, HTTPDigest cancelará automáticamente la petición y enviará al cliente un error.

Si auto_error está establecido a False, cuando el HTTP Digest no está available, en lugar de dar error, el resultado de la dependencia será None.

Esto es útil cuando quieres tener autenticación opcional.

También es útil cuando quieres tener autenticación que puede ser proporcionada de una de múltiples formas opcionales (por ejemplo, en HTTP Digest o en una cookie).

TYPE: bool DEFAULT: True

Código fuente en 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()
Código fuente en 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()
Código fuente en 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(),
    )

Credenciales HTTP

fastapi.security.HTTPAuthorizationCredentials

Bases: BaseModel

Las credenciales de autorización HTTP en el resultado de usar HTTPBearer o HTTPDigest en una dependencia.

El valor del header de autorización HTTP se divide por el primer espacio.

La primera parte es el scheme, la segunda parte son las credentials.

Por ejemplo, en un esquema de token HTTP Bearer, el cliente enviará un header como:

Authorization: Bearer deadbeef12346

En este caso:

  • scheme tendrá el valor "Bearer"
  • credentials tendrá el valor "deadbeef12346"

scheme instance-attribute

scheme

El esquema de autorización HTTP extraído del valor del header.

credentials instance-attribute

credentials

Las credenciales de autorización HTTP extraídas del valor del header.

fastapi.security.HTTPBasicCredentials

Bases: BaseModel

Las credenciales HTTP Basic dadas como resultado de usar HTTPBasic en una dependencia.

Lee más sobre esto en la documentación de FastAPI para HTTP Basic Auth.

username instance-attribute

username

El username de HTTP Basic.

password instance-attribute

password

El password de HTTP Basic.

Autenticación OAuth2

fastapi.security.OAuth2

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

Bases: SecurityBase

Esta es la clase base para autenticación OAuth2, una instancia de ella se usaría como dependencia. Todas las demás clases de OAuth2 heredan de ella y la personalizan para cada flow de OAuth2.

Normalmente no crearías una nueva clase heredando de ella sino que usarías una de las subclases existentes, y quizás combinarlas si quieres soportar múltiples flows.

Lee más sobre esto en la documentación de FastAPI para Seguridad.

PARÁMETRO DESCRIPCIÓN
flows

El diccionario de flows de OAuth2.

TYPE: OAuthFlows | dict[str, dict[str, Any]] DEFAULT: OAuthFlows()

scheme_name

Nombre del esquema de seguridad.

Será incluido en el OpenAPI generado (ej. visible en /docs).

TYPE: str | None DEFAULT: None

description

Descripción del esquema de seguridad.

Será incluido en el OpenAPI generado (ej. visible en /docs).

TYPE: str | None DEFAULT: None

auto_error

Por defecto, si no se proporciona ningún header de Authorization HTTP, requerido para autenticación OAuth2, cancelará automáticamente la petición y enviará al cliente un error.

Si auto_error está establecido a False, cuando el header de Authorization HTTP no está disponible, en lugar de dar error, el resultado de la dependencia será None.

Esto es útil cuando quieres tener autenticación opcional.

También es útil cuando quieres tener autenticación que puede ser proporcionada de una de múltiples formas opcionales (por ejemplo, con OAuth2 o en una cookie).

TYPE: bool DEFAULT: True

Código fuente en 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()

La especificación de OAuth 2 no define el challenge que debería usarse, porque un token Bearer no es realmente la única opción para autenticarse.

Pero declarar cualquier otro challenge de autenticación sería específico de la aplicación ya que no está definido en la especificación.

Por razones prácticas, este método usa el challenge Bearer por defecto, ya que es probablemente el más común.

Si estás implementando un esquema de autenticación OAuth2 distinto a los proporcionados en FastAPI (basados en bearer tokens), quizás quieras sobrescribir esto.

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

Código fuente en 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,
)

Bases: OAuth2

Flow de OAuth2 para autenticación usando un bearer token obtenido con un flow de código OAuth2. Una instancia de ella se usaría como dependencia.

PARÁMETRO DESCRIPCIÓN
tokenUrl

La URL para obtener el token de OAuth2.

TYPE: str

refreshUrl

La URL para refrescar el token y obtener uno nuevo.

TYPE: str | None DEFAULT: None

scheme_name

Nombre del esquema de seguridad.

Será incluido en el OpenAPI generado (ej. visible en /docs).

TYPE: str | None DEFAULT: None

scopes

Los scopes de OAuth2 que serían requeridos por las path operations que usan esta dependencia.

TYPE: dict[str, str] | None DEFAULT: None

description

Descripción del esquema de seguridad.

Será incluido en el OpenAPI generado (ej. visible en /docs).

TYPE: str | None DEFAULT: None

auto_error

Por defecto, si no se proporciona ningún header de Authorization HTTP, requerido para autenticación OAuth2, cancelará automáticamente la petición y enviará al cliente un error.

Si auto_error está establecido a False, cuando el header de Authorization HTTP no está disponible, en lugar de dar error, el resultado de la dependencia será None.

Esto es útil cuando quieres tener autenticación opcional.

También es útil cuando quieres tener autenticación que puede ser proporcionada de una de múltiples formas opcionales (por ejemplo, con OAuth2 o en una cookie).

TYPE: bool DEFAULT: True

Código fuente en 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()

La especificación de OAuth 2 no define el challenge que debería usarse, porque un token Bearer no es realmente la única opción para autenticarse.

Pero declarar cualquier otro challenge de autenticación sería específico de la aplicación ya que no está definido en la especificación.

Por razones prácticas, este método usa el challenge Bearer por defecto, ya que es probablemente el más común.

Si estás implementando un esquema de autenticación OAuth2 distinto a los proporcionados en FastAPI (basados en bearer tokens), quizás quieras sobrescribir esto.

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

Código fuente en 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,
)

Bases: OAuth2

Flow de OAuth2 para autenticación usando un bearer token obtenido con un password. Una instancia de ella se usaría como dependencia.

Lee más sobre esto en la documentación de FastAPI para OAuth2 Simple con Password y Bearer.

PARÁMETRO DESCRIPCIÓN
tokenUrl

La URL para obtener el token de OAuth2. Esta sería la path operation que tiene OAuth2PasswordRequestForm como dependencia.

Lee más sobre esto en la documentación de FastAPI para OAuth2 Simple con Password y Bearer.

TYPE: str

scheme_name

Nombre del esquema de seguridad.

Será incluido en el OpenAPI generado (ej. visible en /docs).

TYPE: str | None DEFAULT: None

scopes

Los scopes de OAuth2 que serían requeridos por las path operations que usan esta dependencia.

Lee más sobre esto en la documentación de FastAPI para OAuth2 Simple con Password y Bearer.

TYPE: dict[str, str] | None DEFAULT: None

description

Descripción del esquema de seguridad.

Será incluido en el OpenAPI generado (ej. visible en /docs).

TYPE: str | None DEFAULT: None

auto_error

Por defecto, si no se proporciona ningún header de Authorization HTTP, requerido para autenticación OAuth2, cancelará automáticamente la petición y enviará al cliente un error.

Si auto_error está establecido a False, cuando el header de Authorization HTTP no está disponible, en lugar de dar error, el resultado de la dependencia será None.

Esto es útil cuando quieres tener autenticación opcional.

También es útil cuando quieres tener autenticación que puede ser proporcionada de una de múltiples formas opcionales (por ejemplo, con OAuth2 o en una cookie).

TYPE: bool DEFAULT: True

refreshUrl

La URL para refrescar el token y obtener uno nuevo.

TYPE: str | None DEFAULT: None

Código fuente en 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.tiangolo.com/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.tiangolo.com/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()

La especificación de OAuth 2 no define el challenge que debería usarse, porque un token Bearer no es realmente la única opción para autenticarse.

Pero declarar cualquier otro challenge de autenticación sería específico de la aplicación ya que no está definido en la especificación.

Por razones prácticas, este método usa el challenge Bearer por defecto, ya que es probablemente el más común.

Si estás implementando un esquema de autenticación OAuth2 distinto a los proporcionados en FastAPI (basados en bearer tokens), quizás quieras sobrescribir esto.

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

Código fuente en 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"},
    )

Formulario de Password OAuth2

fastapi.security.OAuth2PasswordRequestForm

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

Esta es una clase de dependencia para recolectar el username y el password como datos de formulario para un flow de password de OAuth2.

La especificación de OAuth2 dicta que para un flow de password los datos deberían ser recolectados usando datos de formulario (en lugar de JSON) y que debería tener los campos específicos username y password.

Todos los parámetros de inicialización se extraen de la petición.

Lee más sobre esto en la documentación de FastAPI para OAuth2 Simple con Password y Bearer.

Ejemplo

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

Ten en cuenta que para OAuth2 el scope items:read es un solo scope en un string opaco. Podrías tener lógica interna personalizada para separarlo por caracteres de dos puntos (:) o similar, y obtener las dos partes items y read. Muchas aplicaciones hacen eso para agrupar y organizar permisos, podrías hacerlo también en tu aplicación, solo sabe que es específico de la aplicación, no es parte de la especificación.

PARÁMETRO DESCRIPCIÓN
grant_type

La especificación de OAuth2 dice que es obligatorio y DEBE ser el string fijo "password". Sin embargo, esta clase de dependencia es permisiva y permite no pasarlo. Si quieres aplicarlo, usa en su lugar la dependencia OAuth2PasswordRequestFormStrict.

Lee más sobre esto en la documentación de FastAPI para OAuth2 Simple con Password y Bearer.

TYPE: str | None DEFAULT: None

username

String username. La especificación de OAuth2 requiere el nombre exacto del campo username.

Lee más sobre esto en la documentación de FastAPI para OAuth2 Simple con Password y Bearer.

TYPE: str

password

String password. La especificación de OAuth2 requiere el nombre exacto del campo password.

Lee más sobre esto en la documentación de FastAPI para OAuth2 Simple con Password y Bearer.

TYPE: str

scope

Un solo string con realmente varios scopes separados por espacios. Cada scope es también un string.

Por ejemplo, un solo string con:

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

representaría los scopes:

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

Lee más sobre esto en la documentación de FastAPI para OAuth2 Simple con Password y Bearer.

TYPE: str DEFAULT: ''

client_id

Si hay un client_id, puede ser enviado como parte de los campos del formulario. Pero la especificación de OAuth2 recomienda enviar el client_id y el client_secret (si lo hay) usando HTTP Basic auth.

TYPE: str | None DEFAULT: None

client_secret

Si hay un client_secret (y un client_id), pueden ser enviados como parte de los campos del formulario. Pero la especificación de OAuth2 recomienda enviar el client_id y el client_secret (si lo hay) usando HTTP Basic auth.

TYPE: str | None DEFAULT: None

Código fuente en 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.tiangolo.com/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.tiangolo.com/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.tiangolo.com/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.tiangolo.com/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,
)

Bases: OAuth2PasswordRequestForm

Esta es una clase de dependencia para recolectar el username y el password como datos de formulario para un flow de password de OAuth2.

La especificación de OAuth2 dicta que para un flow de password los datos deberían ser recolectados usando datos de formulario (en lugar de JSON) y que debería tener los campos específicos username y password.

Todos los parámetros de inicialización se extraen de la petición.

La única diferencia entre OAuth2PasswordRequestFormStrict y OAuth2PasswordRequestForm es que OAuth2PasswordRequestFormStrict requiere que el cliente envíe el campo de formulario grant_type con el valor "password", que es obligatorio en la especificación de OAuth2 (parece que sin ninguna razón particular), mientras que para OAuth2PasswordRequestForm grant_type es opcional.

Lee más sobre esto en la documentación de FastAPI para OAuth2 Simple con Password y Bearer.

Ejemplo

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

Ten en cuenta que para OAuth2 el scope items:read es un solo scope en un string opaco. Podrías tener lógica interna personalizada para separarlo por caracteres de dos puntos (:) o similar, y obtener las dos partes items y read. Muchas aplicaciones hacen eso para agrupar y organizar permisos, podrías hacerlo también en tu aplicación, solo sabe que es específico de la aplicación, no es parte de la especificación.

la especificación de OAuth2 dice que es obligatorio y DEBE ser el string fijo "password".

Esta dependencia es estricta al respecto. Si quieres ser permisivo, usa en su lugar la clase de dependencia OAuth2PasswordRequestForm.

username: string de username. La especificación de OAuth2 requiere el nombre exacto del campo "username". password: string de password. La especificación de OAuth2 requiere el nombre exacto del campo "password". scope: string opcional. Varios scopes (cada uno un string) separados por espacios. Ej. "items:read items:write users:read profile openid" client_id: string opcional. OAuth2 recomienda enviar el client_id y client_secret (si lo hay) usando HTTP Basic auth, como: client_id:client_secret client_secret: string opcional. OAuth2 recomienda enviar el client_id y client_secret (si lo hay) usando HTTP Basic auth, como: client_id:client_secret

PARÁMETRO DESCRIPCIÓN
grant_type

La especificación de OAuth2 dice que es obligatorio y DEBE ser el string fijo "password". Esta dependencia es estricta al respecto. Si quieres ser permisivo, usa en su lugar la clase de dependencia OAuth2PasswordRequestForm.

Lee más sobre esto en la documentación de FastAPI para OAuth2 Simple con Password y Bearer.

TYPE: str

username

String username. La especificación de OAuth2 requiere el nombre exacto del campo username.

Lee más sobre esto en la documentación de FastAPI para OAuth2 Simple con Password y Bearer.

TYPE: str

password

String password. La especificación de OAuth2 requiere el nombre exacto del campo password.

Lee más sobre esto en la documentación de FastAPI para OAuth2 Simple con Password y Bearer.

TYPE: str

scope

Un solo string con realmente varios scopes separados por espacios. Cada scope es también un string.

Por ejemplo, un solo string con:

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

representaría los scopes:

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

Lee más sobre esto en la documentación de FastAPI para OAuth2 Simple con Password y Bearer.

TYPE: str DEFAULT: ''

client_id

Si hay un client_id, puede ser enviado como parte de los campos del formulario. Pero la especificación de OAuth2 recomienda enviar el client_id y el client_secret (si lo hay) usando HTTP Basic auth.

TYPE: str | None DEFAULT: None

client_secret

Si hay un client_secret (y un client_id), pueden ser enviados como parte de los campos del formulario. Pero la especificación de OAuth2 recomienda enviar el client_id y el client_secret (si lo hay) usando HTTP Basic auth.

TYPE: str | None DEFAULT: None

Código fuente en 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.tiangolo.com/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.tiangolo.com/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.tiangolo.com/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.tiangolo.com/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

Scopes de Seguridad OAuth2 en Dependencias

fastapi.security.SecurityScopes

SecurityScopes(scopes=None)

Esta es una clase especial que puedes definir en un parámetro de una dependencia para obtener los scopes de OAuth2 requeridos por todas las dependencias en la misma cadena.

De esta manera, múltiples dependencias pueden tener diferentes scopes, incluso cuando se usan en la misma path operation. Y con esto, puedes acceder a todos los scopes requeridos en todas esas dependencias en un solo lugar.

Lee más sobre esto en la documentación de FastAPI para scopes de OAuth2.

PARÁMETRO DESCRIPCIÓN
scopes

Esto será llenado por FastAPI.

TYPE: list[str] | None DEFAULT: None

Código fuente en 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 []

La lista de todos los scopes requeridos por las dependencias.

scope_str instance-attribute

scope_str = join(scopes)

Todos los scopes requeridos por todas las dependencias en un solo string separados por espacios, como se define en la especificación de OAuth2.

OpenID Connect

fastapi.security.OpenIdConnect

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

Bases: SecurityBase

Clase de autenticación OpenID Connect. Una instancia de ella se usaría como dependencia.

Aviso: esto es solo un stub para conectar los componentes con OpenAPI en FastAPI, pero no implementa el esquema OpenIdConnect completo, por ejemplo, no usa la URL de OpenIDConnect. Necesitarías crear una subclase e implementarlo en tu código.

PARÁMETRO DESCRIPCIÓN
openIdConnectUrl

La URL de OpenID Connect.

TYPE: str

scheme_name

Nombre del esquema de seguridad.

Será incluido en el OpenAPI generado (ej. visible en /docs).

TYPE: str | None DEFAULT: None

description

Descripción del esquema de seguridad.

Será incluido en el OpenAPI generado (ej. visible en /docs).

TYPE: str | None DEFAULT: None

auto_error

Por defecto, si no se proporciona ningún header de Authorization HTTP, requerido para autenticación OpenID Connect, cancelará automáticamente la petición y enviará al cliente un error.

Si auto_error está establecido a False, cuando el header de Authorization HTTP no está disponible, en lugar de dar error, el resultado de la dependencia será None.

Esto es útil cuando quieres tener autenticación opcional.

También es útil cuando quieres tener autenticación que puede ser proporcionada de una de múltiples formas opcionales (por ejemplo, con OpenID Connect o en una cookie).

TYPE: bool DEFAULT: True

Código fuente en 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()
Código fuente en 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"},
    )