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.
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.
Será incluido en el OpenAPI generado (ej. visible en /docs).
TYPE:str | NoneDEFAULT:None
description
Descripción del esquema de seguridad.
Será incluido en el OpenAPI generado (ej. visible en /docs).
TYPE:str | NoneDEFAULT: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:boolDEFAULT: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,)
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.
Para esto, este método envía un challenge personalizado APIKey.
Código fuente en fastapi/security/api_key.py
defmake_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`. """returnHTTPException(status_code=HTTP_401_UNAUTHORIZED,detail="Not authenticated",headers={"WWW-Authenticate":"APIKey"},)
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.
Será incluido en el OpenAPI generado (ej. visible en /docs).
TYPE:str | NoneDEFAULT:None
description
Descripción del esquema de seguridad.
Será incluido en el OpenAPI generado (ej. visible en /docs).
TYPE:str | NoneDEFAULT: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:boolDEFAULT: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,)
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.
Para esto, este método envía un challenge personalizado APIKey.
Código fuente en fastapi/security/api_key.py
defmake_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`. """returnHTTPException(status_code=HTTP_401_UNAUTHORIZED,detail="Not authenticated",headers={"WWW-Authenticate":"APIKey"},)
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.
Será incluido en el OpenAPI generado (ej. visible en /docs).
TYPE:str | NoneDEFAULT:None
description
Descripción del esquema de seguridad.
Será incluido en el OpenAPI generado (ej. visible en /docs).
TYPE:str | NoneDEFAULT: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:boolDEFAULT: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,)
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.
Para esto, este método envía un challenge personalizado APIKey.
Código fuente en fastapi/security/api_key.py
defmake_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`. """returnHTTPException(status_code=HTTP_401_UNAUTHORIZED,detail="Not authenticated",headers={"WWW-Authenticate":"APIKey"},)
Será incluido en el OpenAPI generado (ej. visible en /docs).
TYPE:str | NoneDEFAULT:None
realm
Realm de autenticación HTTP Basic.
TYPE:str | NoneDEFAULT:None
description
Descripción del esquema de seguridad.
Será incluido en el OpenAPI generado (ej. visible en /docs).
TYPE:str | NoneDEFAULT: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:boolDEFAULT: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_nameorself.__class__.__name__self.realm=realmself.auto_error=auto_error
Será incluido en el OpenAPI generado (ej. visible en /docs).
TYPE:str | NoneDEFAULT:None
description
Descripción del esquema de seguridad.
Será incluido en el OpenAPI generado (ej. visible en /docs).
TYPE:str | NoneDEFAULT: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:boolDEFAULT: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_nameorself.__class__.__name__self.auto_error=auto_error
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.
Será incluido en el OpenAPI generado (ej. visible en /docs).
TYPE:str | NoneDEFAULT:None
description
Descripción del esquema de seguridad.
Será incluido en el OpenAPI generado (ej. visible en /docs).
TYPE:str | NoneDEFAULT: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:boolDEFAULT: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_nameorself.__class__.__name__self.auto_error=auto_error
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.
Será incluido en el OpenAPI generado (ej. visible en /docs).
TYPE:str | NoneDEFAULT:None
description
Descripción del esquema de seguridad.
Será incluido en el OpenAPI generado (ej. visible en /docs).
TYPE:str | NoneDEFAULT: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:boolDEFAULT: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_nameorself.__class__.__name__self.auto_error=auto_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.
defmake_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 """returnHTTPException(status_code=HTTP_401_UNAUTHORIZED,detail="Not authenticated",headers={"WWW-Authenticate":"Bearer"},)
Será incluido en el OpenAPI generado (ej. visible en /docs).
TYPE:str | NoneDEFAULT: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:boolDEFAULT: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,):ifnotscopes: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,)
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.
defmake_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 """returnHTTPException(status_code=HTTP_401_UNAUTHORIZED,detail="Not authenticated",headers={"WWW-Authenticate":"Bearer"},)
Será incluido en el OpenAPI generado (ej. visible en /docs).
TYPE:str | NoneDEFAULT: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:boolDEFAULT:True
refreshUrl
La URL para refrescar el token y obtener uno nuevo.
TYPE:str | NoneDEFAULT: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,):ifnotscopes: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,)
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.
defmake_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 """returnHTTPException(status_code=HTTP_401_UNAUTHORIZED,detail="Not authenticated",headers={"WWW-Authenticate":"Bearer"},)
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.
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.
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 | NoneDEFAULT: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 | NoneDEFAULT: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_typeself.username=usernameself.password=passwordself.scopes=scope.split()self.client_id=client_idself.client_secret=client_secret
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 OAuth2PasswordRequestFormgrant_type es opcional.
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.
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 | NoneDEFAULT: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 | NoneDEFAULT: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,)
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.
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. """),]=scopesor[]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)
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 | NoneDEFAULT:None
description
Descripción del esquema de seguridad.
Será incluido en el OpenAPI generado (ej. visible en /docs).
TYPE:str | NoneDEFAULT: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:boolDEFAULT: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_nameorself.__class__.__name__self.auto_error=auto_error