API

Important

Don’t use the base class flaat.BaseFlaat directly. Use the framework specific classes flaat.flask.Flaat, flaat.aio.Flaat and flaat.fastapi.Flaat instead.

Here is the documentation of the most important modules of flaat with regard to developers, that want to use flaat in the application:

flaat

Python support for OIDC Access Tokens – FLAAT. Use decorators for authorising access to OIDC authenticated REST APIs.

class BaseFlaat

Uses OIDC access tokens to provide authentication and authorization for multiple webframe works. This is the base class. Use the framework specific classes flaat.flask.Flaat, flaat.aio.Flaat and flaat.fastapi.Flaat directly.

You usually use a global instance of Flaat, configure it (see flaat.config.FlaatConfig) and then access its decorators (e.g. is_authenticated(), requires(), inject_object() and access_level()).

get_user_infos_from_access_token(access_token, issuer_hint='')

This method is used to retrieve all infos about an user. You don’t need to call this manually, as the decorators will automatically do it for you.

Parameters

access_token (str) – The access token of the user. The token must not start with ‘Bearer ‘.

Return type

Optional[UserInfos]

Returns

A flaat.user_infos.UserInfos instance with all the infos that could be retrieved. If no info could be retrieved, then None is returned.

authenticate_user(*args, **kwargs)

authenticate user needs the same arguments as the view_func it is called from.

Return type

Optional[UserInfos]

inject_object(infos_to_object=None, key='object', strict=True)

Injects an object into a view function given a method to translate a UserInfos instance into the object. This is useful for injecting user model instances.

Parameters
  • infos_to_object (Optional[Callable[[UserInfos], Any]]) – A function that translates a flaat.user_infos.UserInfos instance to a custom object.

  • key – The key with which the generated object is injected into the kwargs of the view function.

  • strict – If set to True this decorator if fail when there is nothing to inject.

Return type

Callable

Returns

A decorator for a view function.

inject_user_infos(key='user_infos', strict=True)

A decorator which injects the current users flaat.user_infos.UserInfos into the view function.

Parameters
  • key – The key with which the user info is injected.

  • strict – If set to True, an unauthenticated user will not be able to use the view functions and cause an error instead.

Return type

Callable

Returns

A decorator for a view function.

requires(requirements, on_failure=None)
This returns a decorator that will make sure, that the user fits the requirements before the view function is called. If the user does not, an exception

for the respective web framework will be thrown, so the user sees the correct error.

Parameters
  • requirements (Union[Requirement, Callable[[], Requirement], List[Union[Requirement, Callable[[], Requirement]]]]) – One flaat.requirements.Requirement instance or a list of requirements the user needs to fit to have access to the decorated function. If the requirements are wrapped in a callable, it will be lazy evaluated once the view_func is called.

  • on_failure (Optional[Callable[[FlaatException, Optional[UserInfos]], Union[Any, NoReturn]]]) – Optional function to customize the handling of an error. This function can either raise an exception or return a response which should be returned in place of the response from the view function.

Return type

Callable

Returns

A decorator for a view function.

access_level(access_level_name, on_failure=None)
Parameters
  • access_level_name (str) – The name of the access_level that the user needs to use the view function.

  • on_failure (Optional[Callable[[FlaatException, Optional[UserInfos]], Union[Any, NoReturn]]]) – Can be used to either deliver an error response to the user, or raise a specific exception.

Return type

Callable

Returns

A decorator, that can be used to decorate a view function.

is_authenticated(on_failure=None)

This can be used to make sure that users are identified (as in they have a subject and an issuer). If you actually want to access the users infos we recommend using inject_user_infos() or inject_object() instead.

Parameters

on_failure (Optional[Callable[[FlaatException, Optional[UserInfos]], Union[Any, NoReturn]]]) – Can be used to either deliver an error response to the user, or raise a specific exception.

Return type

Callable

Returns

A decorator for a view function

class AuthWorkflow(flaat, user_requirements=None, request_requirements=None, process_arguments=None, on_failure=None, ignore_no_authn=False)

This class can be used if you need maximum customizability for your decorator. It encapsulates the complete workflow of a decorator.

Parameters
  • flaat (BaseFlaat) – The flaat instance that is currently in use.

  • user_requirements (Union[Requirement, Callable[[], Requirement], List[Union[Requirement, Callable[[], Requirement]]], None]) – Requirement which the user all needs to match, like with requires().

  • request_requirements (Union[Callable[[UserInfos, tuple, dict], CheckResult], List[Callable[[UserInfos, tuple, dict], CheckResult]], None]) – A callable which determines if a users request is allowed to proceed. This function is handy if you want to evaluate the arguments for the view function before against the users permissions.

  • process_arguments (Optional[Callable[[UserInfos, tuple, dict], Tuple[tuple, dict]]]) – As with inject_object(), this can be used to inject data into the view function.

  • on_failure (Optional[Callable[[FlaatException, Optional[UserInfos]], Union[Any, NoReturn]]]) – Can be used to either deliver an error response to the user, or raise a specific exception.

  • ignore_no_authn – If set to True a failing authentication of the user will not cause exceptions.

Returns

A class instance, which is used by decorating view functions with its decorate_view_func() method.

decorate_view_func(view_func)
Parameters

view_func (Callable) – The view function to decorate.

Return type

Callable

Returns

The decorated view function.

flaat.user_infos

class UserInfos(access_token_info, user_info, introspection_info)

Infos about an access token and the user it belongs to. This class acts like a dictionary with regards to claims. So infos[“foo”] will give you the claim if it does exist in one of the underlying dicts.

access_token_info: Optional[Any] = None

Is set to AccessTokenInfo if the respective access token was a JWT.

user_info: dict

user_info is the user info dictionary from the user info endpoint of the issuer.

introspection_info: Optional[dict] = None

Is the data returned from the token intropsection endpoint of the issuer.

post_process_dictionaries()

post_process_dictionaries can be used to do post processing on the raw dictionaries after initialization. Extend this class and overwrite this method to do custom post processing. Make sure to call super().post_process_dictionaries(), so the post processing done here is picked up.

property valid_for_secs: Optional[int]

Is set if we now about the expiry of these user infos.

Return type

Optional[int]

property issuer: str

The issuer of the access token

Return type

str

property subject: str

The users subject at the issuer

Return type

str

toJSON()

Render these infos to JSON

Return type

str

flaat.access_tokens

class AccessTokenInfo(complete_decode, verification=typing.Optional[dict])

Infos from a JWT access token

header: dict

The JWTs JOSE header

body: dict

The JWTs data payload

signature: str

The JWTs JWS signature

verification: Optional[dict]

Infos about the verification of the JWT. If set to None, then the JWT data is unverified.

class FlaatPyJWKClient(uri, cache_keys=True, max_cached_keys=16)

Fixes the jwt.PyJWKClient class:

  • get_signing_keys
    • does not call self.get_jwk_set(), since it fails when “enc” keys are present

    • returns only keys used for signing (e.g. filters out keys with “use” == “enc”)

  • get_signing_key_from_jwt
    • tries to retrieve keys by id only if “kid” is specified in token header

    • otherwise, it tries to infer the key type (“kty”) from the algorithm used to sign the token (“alg”)

    • “alg” is always present in JWT header

  • an additional method get_signing_key_by_alg

flaat.requirements

This module contains classes to express diverse requirements which a user needs to satisfy in order to use a view function.

The convenience functions get_claim_requirement() and get_vo_requirement() are recommended to construct individual requirements.

If you want to combine multiple requirements use the “meta requirements” AllOf and N_Of.

class CheckResult(is_satisfied, message, data=None)

CheckResult is the result of an is_satisfied_by check

is_satisfied: bool

Is True if the requirement was satisfied by the user info

message: str

Message describing the check result. This could be an error message.

class Requirement

Requirement is the base class of all requirements. The have a method is_satisfied_by which returns a CheckResult instance.

class Satisfied

Satisfied is always satisfied

class Unsatisfiable

Unsatisfiable is never satisfied

class IsTrue(func)

IsTrue is satisfied if the provided func evaluates to True

Parameters

func (Callable[[UserInfos], bool]) – A function that is used to determine if a user info satisfies custom requirements.

class MetaRequirement(*reqs)

MetaRequirement is a requirements consisting of multiple sub-requirements Use the childs AllOf or N_Of directly.

property requirements: List[flaat.requirements.Requirement]

do the lazy loading of callables

Return type

List[Requirement]

class AllOf(*reqs)

AllOf is satisfied if all of its sub-requirements are satisfied. If there are no sub-requirements, this class is never satisfied.

class N_Of(n, *reqs)

N_Of is satisfied if at least n of its sub-requirements are satisfied. If there are no sub-requirements, this class is never satisfied.

class OneOf(*reqs)

OneOf is satisfied if at least one of its sub-requirements are satisfied. If there are no sub-requirements, this class is never satisfied.

class HasSubIss

HasSubIss is satisfied if the user has a subject and an issuer

class HasClaim(required, claim)

HasClaim is satisfied if the user has the specified claim value

class HasAudience(required, claim)

HasAudience is satisfied if the user’s access token was issued for a specific audience

class HasAARCEntitlement(required, claim)

HasAARCEntitlement is satisfies if the user has the provided AARC-G002/G069 entitlement If the argument required is not a parseable AARC entitlement, we revert to equals comparisons.

get_claim_requirement(required, claim, match='all')
Parameters
  • required (Union[str, List[str]]) – The claim values that the user needs to have.

  • claim (str) – The claim of the value in required, e.g. eduperson_entitlement.

  • match (Union[str, int]) – May be “all” if all required values need to be matched, or “one” or an integer if a specific amount needs to be matched.

Return type

Requirement

Returns

A requirement that is satisfied if the user has the claim value(s) of required.

get_vo_requirement(required, claim, match='all')

Equivalent to get_claim_requirement(), but works for both groups and AARC entitlements.

Return type

Requirement

get_audience_requirement(required)

Equivalent to get_claim_requirement(), but specific to audience claim.

Return type

Requirement

flaat.exceptions

exception FlaatException

An error occured inside flaat. The cause can be misconfiguration or other not user related errors. This exception will cause a response with status 500 if unhandled.

exception FlaatForbidden

The user is forbidden from using the service. This exception will cause a response with status 403 if unhandled.

exception FlaatUnauthenticated

The users identity could not be determined. Probably there was no access token or the access tokens issuer could not be determined.

This exception will cause a response with status 401 if unhandled.