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
AuthMiddleware
middleware.- abstract authenticate(attributes: falcon_auth2.utils.classes.RequestAttributes) dict [source]
Authenticates the request and returns the authenticated user.
If a request cannot be authenticated a backed should raise:
AuthenticationFailure
to indicate that the request can be handled by this backend, but the authentication fails.BackendNotApplicable
if the provided request cannot be handled by this backend. This is usually raised by theGetter
used by the backend to process the request.UserNotFound
when 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, *, challenges: Optional[Iterable[str]] = 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
RequestAttributes
object as well as any relevant data extracted from the request by the backend. The arguments passed touser_loader
will vary depending on theAuthBackend
. It should return the user identified by the request, orNone
if 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-Authenticate
header in case of errors. Defaults toNone
.
- load_user(attributes: falcon_auth2.utils.classes.RequestAttributes, *args, **kwargs) Any [source]
Invokes the provided
user_loader
callable to allow the app to retrieve the user record. If no such record is found, raises aUserNotFound
exception.- Parameters
attributes (RequestAttributes) – The request attributes.
*args – Positional arguments to pass to the
user_loader
callable.**kwargs – Keyword arguments to pass to the
user_loader
callable.
- Returns
Any – The loaded user object returned by
user_loader
.
Authentication Backends
BasicAuthBackend
- class falcon_auth2.backends.BasicAuthBackend(user_loader: Callable, *, auth_header_type: str = 'Basic', getter: Optional[falcon_auth2.getter.Getter] = None)[source]
Implements the ‘Basic’ HTTP Authentication Scheme.
Clients should authenticate by passing the credential in the format
username:password
encoded inbase64
in theAuthorization
HTTP 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
RequestAttributes
object and the username and password credentials extracted from the request using the providedgetter
. It should return the user identified by the credentials, orNone
if 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
Authorization
header. This value is added to thechallenges
in case of errors. Defaults to"Basic"
.Note
When passing a custom
getter
this 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
base64
encoded string with the credentials in the formatusername:password
. Defaults toAuthHeaderGetter
initialized with the providedauth_header_type
.
- authenticate(attributes: falcon_auth2.utils.classes.RequestAttributes) dict [source]
Authenticates the request and returns the authenticated user.
JWTAuthBackend
- class falcon_auth2.backends.JWTAuthBackend(user_loader: Callable, key: Union[str, bytes, dict, Callable[[dict, dict], Union[str, bytes]]], *, auth_header_type: str = 'Bearer', getter: Optional[falcon_auth2.getter.Getter] = None, algorithms: Optional[Union[str, List[str]]] = 'HS256', claims_options: Optional[dict] = 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 Authlib 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
RequestAttributes
object and the token payload obtained after a successful validation. It should return the user identified by the token, orNone
if 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 (str, bytes, dict, Callable) – The key to use to decode the tokens. This parameter is passed to the
JsonWebToken.decode()
method and is used to verify the signature of the token. A key can be passed as string or bytes. Dynamic keys are also supported by passing a “JWK set” dict or a callable that is called with the token header and payload and returns the key to use to validate the current token signature. See Use dynamic keys for additional details on the supported values.
- Keyword Arguments
auth_header_type (string, optional) –
The type of authentication required in the
Authorization
header. This value is added to thechallenges
in case of errors. Defaults to"Bearer"
.Note
When passing a custom
getter
this 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
AuthHeaderGetter
initialized 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 RFC7518: JSON Web 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: falcon_auth2.utils.classes.RequestAttributes) dict [source]
Authenticates the request and returns the authenticated user.
- default_claims()[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_options
parameter when instanciating this class.See JWT Payload Claims Validation for additional details on the
claims_options
format.
GenericAuthBackend
- class falcon_auth2.backends.GenericAuthBackend(user_loader: Callable, getter: falcon_auth2.getter.Getter, *, payload_key: Optional[str] = None, challenges: Optional[Iterable[str]] = None)[source]
Generic authentication backend that delegates the verification of the authentication information retried from the request by the provided
getter
to theuser_loader
callable.This backend can be used to quickly implement custom authentication schemes or as an adapter to other authentication libraries.
Depending on the
getter
provided, 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
RequestAttributes
object and the information extracted from the request using the providedgetter
. It should return the user identified by the request, orNone
if 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_loader
callable.
- 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
. UseNone
to disable this functionality. Defaults toNone
.challenges (Optional[Iterable[str]], optional) – One or more authentication challenges to use as the value of the
WWW-Authenticate
header in case of errors. Defaults toNone
.
- authenticate(attributes: falcon_auth2.utils.classes.RequestAttributes) dict [source]
Authenticates the request and returns the authenticated user.
NoAuthBackend
- class falcon_auth2.backends.NoAuthBackend(user_loader: Callable, *, challenges: Optional[Iterable[str]] = None)[source]
No authentication backend.
This backend does not perform any authentication check. It can be used with the
MultiAuthBackend
in 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
RequestAttributes
object and returns a default unauthenticated user ( alternatively the user identified by a custom authentication workflow) orNone
if 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-Authenticate
header in case of errors. Defaults toNone
.
- authenticate(attributes: falcon_auth2.utils.classes.RequestAttributes) dict [source]
Authenticates the request and returns the authenticated user.
Meta Backends
CallBackBackend
- class falcon_auth2.backends.CallBackBackend(backend: falcon_auth2.backends.base.AuthBackend, *, on_success: Optional[Callable] = None, on_failure: Optional[Callable] = 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
, thebackend
and 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
, thebackend
and 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
backend
because it will be propagated afteron_failure
invocation ends. The callable may choose to raise a different exception instead.
- authenticate(attributes: falcon_auth2.utils.classes.RequestAttributes) dict [source]
Authenticates the request and returns the authenticated user.
MultiAuthBackend
- class falcon_auth2.backends.MultiAuthBackend(backends: Iterable[falcon_auth2.backends.base.AuthBackend], *, continue_on: Optional[Callable] = 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
BackendNotApplicable
if 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
True
if processing should continue to the next backend orFalse
if 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 aBackendNotApplicable
exception.Note
This callable is only invoked if a backend raises an instance of
HTTPUnauthorized
or one of it’s subclasses. All other exception types are propagated.
- authenticate(attributes: falcon_auth2.utils.classes.RequestAttributes)[source]
Authenticates the request and returns the authenticated user.