Backends implementations
Base classes
AuthBackend
- class falcon_auth2.backends.AuthBackend[source]
Base class that defines the signature of the
authenticate()method.Backend must subclass of this class to be used by the
AuthMiddlewaremiddleware.- abstractmethod authenticate(attributes: RequestAttributes) dict[Any, Any][source]
Authenticates the request and returns the authenticated user.
If a request cannot be authenticated a backed should raise:
AuthenticationFailureto indicate that the request can be handled by this backend, but the authentication fails.BackendNotApplicableif the provided request cannot be handled by this backend. This is usually raised by theGetterused by the backend to process the request.UserNotFoundwhen no user could be loaded with the provided credentials.
- Parameters:
attributes (RequestAttributes) – The current request attributes. It’s a named tuple which contains the falcon request and response objects, the activated resource and the parameters matched in the url.
- Returns:
dict – A dictionary with a required
"user"key containing the authenticated user. This dictionary may optionally contain additional keys specific to this backend. If the"backend"key is specified, the middleware will not override it.
BaseAuthBackend
- class falcon_auth2.backends.BaseAuthBackend(user_loader: Callable[[...], Any], *, challenges: Iterable[str] | None = None)[source]
Utility class that handles calling a provided callable to load an user from the authentication information of the request in the
load_user()method.- Parameters:
user_loader (Callable) –
A callable object that is called with the
RequestAttributesobject as well as any relevant data extracted from the request by the backend. The arguments passed touser_loaderwill vary depending on theAuthBackend. It should return the user identified by the request, orNoneif no user could be not found. When using falcon in async mode (asgi), this function may also be async.Note
An error will be raised if an async function is used when using falcon in sync mode (wsgi).
Note
Exceptions raised in this callable are not handled directly, and are surfaced to falcon.
- Keyword Arguments:
challenges (Optional[Iterable[str]], optional) – One or more authentication challenges to use as the value of the
WWW-Authenticateheader in case of errors. Defaults toNone.
- load_user(attributes: RequestAttributes, *args: Any, **kwargs: Any) Any[source]
Invokes the provided
user_loadercallable to allow the app to retrieve the user record. If no such record is found, raises aUserNotFoundexception.- Parameters:
attributes (RequestAttributes) – The request attributes.
*args – Positional arguments to pass to the
user_loadercallable.**kwargs – Keyword arguments to pass to the
user_loadercallable.
- Returns:
Any – The loaded user object returned by
user_loader.
Authentication Backends
BasicAuthBackend
- class falcon_auth2.backends.BasicAuthBackend(user_loader: Callable[[RequestAttributes, str, str], Any], *, auth_header_type: str = 'Basic', getter: Getter | None = None)[source]
Implements the ‘Basic’ HTTP Authentication Scheme.
Clients should authenticate by passing the credential in the format
username:passwordencoded inbase64in theAuthorizationHTTP header, prepending it with the type specified in the settingauth_header_type. For example, the user"Aladdin"would provide his password,"open sesame", with the header:Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
- Parameters:
user_loader (Callable) –
A callable object that is called with the
RequestAttributesobject and the username and password credentials extracted from the request using the providedgetter. It should return the user identified by the credentials, orNoneif no user could be not found. When using falcon in async mode (asgi), this function may also be async.Note
An error will be raised if an async function is used when using falcon in sync mode (wsgi).
Note
Exceptions raised in this callable are not handled directly, and are surfaced to falcon.
- Keyword Arguments:
auth_header_type (string, optional) –
The type of authentication required in the
Authorizationheader. This value is added to thechallengesin case of errors. Defaults to"Basic".Note
When passing a custom
getterthis value is only used to generate thechallenges, since the provided getter will be used to obtain the credentials to authenticate.getter (Optional[Getter]) – Getter used to extract the authentication information from the request. When using a custom getter, the returned value must be a
base64encoded string with the credentials in the formatusername:password. Defaults toAuthHeaderGetterinitialized with the providedauth_header_type.
- authenticate(attributes: RequestAttributes) dict[str, Any][source]
Authenticates the request and returns the authenticated user.
JWTAuthBackend
- class falcon_auth2.backends.JWTAuthBackend(user_loader: Callable[[RequestAttributes, dict[str, Any]], Any], key: OctKey | RSAKey | ECKey | OKPKey | KeySet | Callable[[GuestProtocol], OctKey | RSAKey | ECKey | OKPKey | KeySet], *, auth_header_type: str = 'Bearer', getter: Getter | None = None, algorithms: str | list[str] | None = 'HS256', claims_options: dict[str, ClaimsOption] | None = None, leeway: int = 0)[source]
Implements the JSON Web Token (JWT) standard.
Clients should authenticate by passing the token key in the Authorization HTTP header, prepending it with the type specified in the setting
auth_header_type.This backend uses the joserfc library to handle the validation of the tokens. See also its JSON Web Token (JWT) documentation for additional details on the authentication library features.
- Parameters:
user_loader (Callable) –
A callable object that is called with the
RequestAttributesobject and the token payload obtained after a successful validation. It should return the user identified by the token, orNoneif no user could be not found. The token is extracted from the request using the providedgetter. When using falcon in async mode (asgi), this function may also be async.Note
An error will be raised if an async function is used when using falcon in sync mode (wsgi).
Note
Exceptions raised in this callable are not handled directly, and are surfaced to falcon.
key (KeyFlexible) – The key to use to decode the tokens. This parameter is passed to the
joserfc.jwt.decode()method and is used to verify the signature of the token. A key can be passed as static value or a key set or a callable. See The key parameter for additional details on the supported values.
- Keyword Arguments:
auth_header_type (string, optional) –
The type of authentication required in the
Authorizationheader. This value is added to thechallengesin case of errors. Defaults to"Bearer".Note
When passing a custom
getterthis value is only used to generate thechallenges, since the provided getter will be used to obtain the credentials to authenticate.getter (Optional[Getter]) – Getter used to extract the authentication token from the request. When using a custom getter, the returned value must be a valid jwt token in string form (ie not yet parsed). Defaults to
AuthHeaderGetterinitialized with the providedauth_header_type.algorithms (str, List[str]) – The signing algorithm(s) that should be supported. Using a list multiple values may be provided. Defaults to
"HS256". Allowed values are listed at Algorithms.claims_options (dict) – The claims to validate in the token. By default the value returned by
JWTAuthBackend.default_claims()is used.leeway (int) – Leeway in seconds to pass to the
JWTClaims.validate()call to account for clock skew. Defaults to 0.
- authenticate(attributes: RequestAttributes) dict[str, Any][source]
Authenticates the request and returns the authenticated user.
- default_claims() dict[str, ClaimsOption][source]
Returns the default claims to verify in the tokens.
The default claims check that the ‘iss’, ‘sub’, ‘aud’, ‘exp’, ‘nbf’, ‘iat’ are present in the token.
Subclasses can choose to override this method. The claims may also be passed using the
claims_optionsparameter when instantiating this class.See Validate claims for additional details on the
claims_optionsformat.
GenericAuthBackend
- class falcon_auth2.backends.GenericAuthBackend(user_loader: Callable[[RequestAttributes, str], Any], getter: Getter, *, payload_key: str | None = None, challenges: Iterable[str] | None = None)[source]
Generic authentication backend that delegates the verification of the authentication information retried from the request by the provided
getterto theuser_loadercallable.This backend can be used to quickly implement custom authentication schemes or as an adapter to other authentication libraries.
Depending on the
getterprovided, this backend can be used to authenticate the an user using a session cookie or using a parameter as token.- Parameters:
user_loader (Callable) –
A callable object that is called with the
RequestAttributesobject and the information extracted from the request using the providedgetter. It should return the user identified by the request, orNoneif no user could be not found. When using falcon in async mode (asgi), this function may also be async.Note
An error will be raised if an async function is used when using falcon in sync mode (wsgi).
Note
Exceptions raised in this callable are not handled directly, and are surfaced to falcon.
getter (Getter) – Getter used to extract the authentication information from the request. The returned value is passed to the
user_loadercallable.
- Keyword Arguments:
payload_key (Optional[str], optional) – It defines a key in the dict returned by the
authentication()method that will contain data obtained from the request by thegetter. UseNoneto disable this functionality. Defaults toNone.challenges (Optional[Iterable[str]], optional) – One or more authentication challenges to use as the value of the
WWW-Authenticateheader in case of errors. Defaults toNone.
- authenticate(attributes: RequestAttributes) dict[Any, Any][source]
Authenticates the request and returns the authenticated user.
NoAuthBackend
- class falcon_auth2.backends.NoAuthBackend(user_loader: Callable[[...], Any], *, challenges: Iterable[str] | None = None)[source]
No authentication backend.
This backend does not perform any authentication check. It can be used with the
MultiAuthBackendin order to provide a fallback for an unauthenticated user or to implement a complitely custom authentication workflow.- Parameters:
user_loader (Callable) –
A callable object that is called with the
RequestAttributesobject and returns a default unauthenticated user ( alternatively the user identified by a custom authentication workflow) orNoneif no user could be not found. When using falcon in async mode (asgi), this function may also be async.Note
An error will be raised if an async function is used when using falcon in sync mode (wsgi).
Note
Exceptions raised in this callable are not handled directly, and are surfaced to falcon.
- Keyword Arguments:
challenges (Optional[Iterable[str]], optional) – One or more authentication challenges to use as the value of the
WWW-Authenticateheader in case of errors. Defaults toNone.
- authenticate(attributes: RequestAttributes) dict[Any, Any][source]
Authenticates the request and returns the authenticated user.
Meta Backends
CallBackBackend
- class falcon_auth2.backends.CallBackBackend(backend: AuthBackend, *, on_success: Callable[[RequestAttributes, AuthBackend, dict[str, Any]], Any] | None = None, on_failure: Callable[[RequestAttributes, AuthBackend, Exception], Any] | None = None)[source]
Meta-Backend used to notify when another backend has success and/or fails to authenticate a request.
This backend delegates all the authentication actions to the provided
backend.- Parameters:
backend (AuthBackend) – The backend that will be used to authenticate the requests.
- Keyword Arguments:
on_success (Optional[Callable], optional) –
Callable object that will be invoked with the
RequestAttributes, thebackendand the authentication result (the dict that will be placed in the request context by the middleware) after a successful request authentication. When using falcon in async mode (asgi), this function may also be async. Defaults toNone.Note
An error will be raised if an async function is used when using falcon in sync mode (wsgi).
on_failure (Optional[Callable], optional) –
Callable object that will be invoked with the
RequestAttributes, thebackendand the raised exception after a failed request authentication. When using falcon in async mode (asgi), this function may also be async. Defaults toNone.Note
An error will be raised if an async function is used when using falcon in sync mode (wsgi).
Note
This method cannot be used to suppress an exception raised by the
backendbecause it will be propagated afteron_failureinvocation ends. The callable may choose to raise a different exception instead.
- authenticate(attributes: RequestAttributes) dict[Any, Any][source]
Authenticates the request and returns the authenticated user.
MultiAuthBackend
- class falcon_auth2.backends.MultiAuthBackend(backends: Iterable[AuthBackend], *, continue_on: Callable[[AuthBackend, Exception], bool] | None = None)[source]
Meta-Backend used to combine multiple authentication backends.
This backend successfully authenticates a request if one of the provided backends can authenticate the request or raises
BackendNotApplicableif no backend can authenticate it.This backend delegates all the authentication actions to the provided
backends.- Parameters:
backends (Iterable[AuthBackend]) – The backends to use. They will be used in order.
- Keyword Arguments:
continue_on (Callable) –
A callable object that is called when a backend raises an exception. It should return
Trueif processing should continue to the next backend orFalseif it should stop by re-raising the backend exception. The callable takes the backend and the raised exception as parameters. The default implementation continues processing if any backend raises aBackendNotApplicableexception.Note
This callable is only invoked if a backend raises an instance of
HTTPUnauthorizedor one of it’s subclasses. All other exception types are propagated.
- authenticate(attributes: RequestAttributes) dict[Any, Any][source]
Authenticates the request and returns the authenticated user.