Skip to main content

authentication

General authentication classes for external service interactions.

Module

Functions

is_token_valid

def is_token_valid(expires: datetime)> bool:

Check if a token is still valid with a 1-minute buffer.

Classes

BearerAuthSession

class BearerAuthSession(bearer_token: str):

Session implementation that uses bearer authentication and auto-retry.

Has no notion of token expiration or (re)authentication, simply using the provided token as-is. If reauthentication is required, see ExternallyManagedJWTSession.

Initializes a BearerAuthSession with the provided bearer token.

Methods


request

def request(    self,    method: str | bytes,    url: str | bytes,    params: Optional[MutableMapping[str, Any]] = None,    data: Any = None,    headers: Optional[MutableMapping[str, str]] = None,    **kwargs: Any,)> requests.models.Response:

Performs an HTTP request.

Overrides requests.session.request, appending our access token to the request headers or API keys if present.

ExternallyManagedJWT

class ExternallyManagedJWT(    *,    jwt: Optional[str] = None,    expires: Optional[datetime] = None,    get_token: Callable[[], tuple[str, datetime]],):

Externally managed JWT.

The get_token callable may raise (e.g. AuthenticationError) if the external source cannot provide a token; GenericExternallyManagedJWTHandler will propagate that as AuthenticationError.

Variables

  • static jwt : Optional[str]

ExternallyManagedJWTSession

class ExternallyManagedJWTSession(    authentication_handler: GenericExternallyManagedJWTHandler,):

Manages session-based interactions with authentication handled externally.

Extends requests.Session, appending an access token to the authorization of any requests made if an access token is present

When the token expires it will request a new token prior to sending the web request.

Variables

  • authenticated : bool - Returns true if we have an unexpired access token.
  • request_headers : dict[str, typing.Any] - Returns metadata for authenticating external service.

    Handles (re)authentication against the external service if needed.

Methods


authenticate

def authenticate(self)> None:

Authenticates session to allow protected requests.

request

def request(    self,    method: str | bytes,    url: str | bytes,    params: Optional[MutableMapping[str, Any]] = None,    data: Any = None,    headers: Optional[MutableMapping[str, str]] = None,    **kwargs: Any,)> requests.models.Response:

Performs an HTTP request.

Overrides requests.session.request, appending our access token to the request headers or API keys if present.

GenericExternallyManagedJWTHandler

class GenericExternallyManagedJWTHandler(    jwt: Optional[str],    expires: Optional[datetime],    get_token: Callable[[], tuple[str, datetime]],    **kwargs: Any,):

Authenticates user via JWT from an external source.

The Bitfount library hands responsibility for management of the token to the external source.

Whenever a new token is needed it makes a call to the get_token hook which provides one.

Creates a new instance of GenericExternallyManagedJWTHandler.

Can be supplied an initial JWT and expiration time to use or ignore these and rely on the provided hook to get the first token.

Arguments

  • jwt: Optional. Initial JWT token to use. If provided, expires must also be provided.
  • expires: Optional. Initial expiration time to use. If provided, jwt must also be provided.
  • get_token: Callable that returns a tuple of a JWT and its expiration time.
  • ****kwargs**: Other kwargs to be passed to the superclass.

Variables

  • authenticated : bool - Whether the token is still valid.
  • request_headers : dict[str, typing.Any] - Header for authenticated requests.

    Checking that the call is authenticated is the responsibility of the calling code.

    Raises: AuthenticationError: If the JWT is not present or is expired.

Methods


authenticate

def authenticate(self, max_retries: int = 3)> None:

Retrieves a token from the token source.

Calls the hook provided on object creation to retrieve a new token. Any exception from get_token (e.g. retrieval timeout, no credentials) is re-raised as AuthenticationError. Includes retry logic with exponential backoff for the case where the token source returns an expired token while refreshing.

Raises

  • AuthenticationError: If get_token raises or authentication fails after all retries.

get_valid_token

def get_valid_token(self)> str:

Get a valid token to use.

get_valid_token_with_expiry

def get_valid_token_with_expiry(self)> tuple[str, datetime.datetime]:

Get a valid token and its expiry time.

JWT

class JWT(jwt: str, expires: datetime):

Thin container for JSON web token and its expiry.

Variables

  • static jwt : str