Skip to content

TokenPayload#

authx.schema.TokenPayload #

Bases: BaseModel

A comprehensive Pydantic model for managing JSON Web Token (JWT) payloads with advanced token lifecycle handling.

Provides robust functionality for creating, validating, and manipulating authentication tokens with flexible configuration and extensive metadata support.

ATTRIBUTE DESCRIPTION
jti

Unique token identifier.

TYPE: Optional[str]

iss

Token issuer.

TYPE: Optional[str]

sub

Subject (user) identifier.

TYPE: str

aud

Token audience.

TYPE: Optional[StringOrSequence]

exp

Token expiration time.

TYPE: Optional[DateTimeExpression]

nbf

Token not-before time.

TYPE: Optional[Union[Numeric, DateTimeExpression]]

iat

Token issued-at time.

TYPE: Optional[Union[Numeric, DateTimeExpression]]

type

Token type (access or refresh).

TYPE: Optional[str]

csrf

Cross-Site Request Forgery token.

TYPE: Optional[str]

scopes

List of token scopes.

TYPE: Optional[list[str]]

fresh

Flag indicating if the token is freshly issued.

TYPE: bool

METHOD DESCRIPTION
issued_at

Converts issued time to datetime.

expiry_datetime

Calculates token expiration datetime.

time_until_expiry

Calculates remaining time before token expiration.

time_since_issued

Calculates time elapsed since token issuance.

has_scopes

Checks if token has specific scopes.

encode

Creates a JWT token.

decode

Decodes and validates a JWT token.

model_config class-attribute instance-attribute #

model_config = ConfigDict(extra='allow', from_attributes=True)

jti class-attribute instance-attribute #

jti = Field(default_factory=get_uuid)

iss class-attribute instance-attribute #

iss = None

sub instance-attribute #

sub

aud class-attribute instance-attribute #

aud = None

exp class-attribute instance-attribute #

exp = None

nbf class-attribute instance-attribute #

nbf = None

iat class-attribute instance-attribute #

iat = Field(default_factory=lambda: int(get_now_ts()))

type class-attribute instance-attribute #

type = Field(default='access', description='Token type')

csrf class-attribute instance-attribute #

csrf = ''

scopes class-attribute instance-attribute #

scopes = None

fresh class-attribute instance-attribute #

fresh = False

extra_dict property #

extra_dict

Retrieve additional fields not defined in the base Pydantic model schema.

Provides a dictionary of extra fields with version-specific compatibility for Pydantic v1 and v2.

RETURNS DESCRIPTION
dict[str, Any]

A dictionary containing additional fields beyond the model's defined schema.

issued_at property #

issued_at

Convert the token's issued-at timestamp to a datetime object.

Transforms the issued-at (iat) claim into a standardized UTC datetime representation.

RETURNS DESCRIPTION
datetime

A datetime object representing the token's issuance time.

RAISES DESCRIPTION
TypeError

If the issued-at claim is not a float, int, or datetime object.

expiry_datetime property #

expiry_datetime

Convert the token's expiration claim to a precise datetime object.

Transforms the expiration (exp) claim into a standardized UTC datetime representation, supporting multiple input types.

RETURNS DESCRIPTION
datetime

A datetime object representing the token's expiration time.

RAISES DESCRIPTION
TypeError

If the expiration claim is not a float, int, datetime, or timedelta object.

time_until_expiry property #

time_until_expiry

Calculate the remaining time before the token expires.

Computes the time difference between the token's expiration datetime and the current time.

RETURNS DESCRIPTION
timedelta

A timedelta object representing the remaining time until token expiration.

time_since_issued property #

time_since_issued

Calculate the elapsed time since the token was issued.

Computes the time difference between the current time and the token's issued datetime.

RETURNS DESCRIPTION
timedelta

A timedelta object representing the time elapsed since token issuance.

Config #

Configuration class for Pydantic model with extra field handling.

Allows additional fields beyond the defined model schema to be included during model creation.

extra class-attribute instance-attribute #
extra = allow

has_scopes #

has_scopes(*scopes)

Check if the token contains all specified scopes.

Verifies whether the token's scopes include all the requested scope values.

PARAMETER DESCRIPTION
*scopes

TYPE: Sequence[str] DEFAULT: ()

PARAMETER DESCRIPTION
*scopes

Variable number of scope strings to check against the token's scopes.

TYPE: Sequence[str] DEFAULT: ()

RETURNS DESCRIPTION
bool

A boolean indicating whether all specified scopes are present in the token.

Source code in authx/schema.py
def has_scopes(self, *scopes: Sequence[str]) -> bool:
    """Check if the token contains all specified scopes.

    Verifies whether the token's scopes include all the requested scope values.

    Args:
        *scopes: Variable number of scope strings to check against the token's scopes.

    Returns:
        A boolean indicating whether all specified scopes are present in the token.
    """
    # if `self.scopes`` is None, the function will immediately return False.
    # If `self.scopes`` is not None, it will check if all elements in scopes are in `self.scopes``.
    return all(s in self.scopes for s in scopes) if self.scopes is not None else False

encode #

encode(key, algorithm='HS256', ignore_errors=True, headers=None, data=None)

Generate a JSON Web Token (JWT) with the current payload's claims and configuration.

Creates a signed token using the specified cryptographic key and algorithm, incorporating all token metadata.

PARAMETER DESCRIPTION
key

TYPE: str

algorithm

TYPE: AlgorithmType DEFAULT: 'HS256'

ignore_errors

TYPE: bool DEFAULT: True

headers

TYPE: Optional[dict[str, Any]] DEFAULT: None

data

TYPE: Optional[dict[str, Any]] DEFAULT: None

PARAMETER DESCRIPTION
key

The cryptographic key used for token signing.

TYPE: str

algorithm

The cryptographic algorithm for token signing. Defaults to HS256.

TYPE: AlgorithmType DEFAULT: 'HS256'

ignore_errors

Flag to suppress potential encoding errors. Defaults to True.

TYPE: bool DEFAULT: True

headers

Optional custom headers to include in the token.

TYPE: Optional[dict[str, Any]] DEFAULT: None

data

Optional additional data to embed in the token.

TYPE: Optional[dict[str, Any]] DEFAULT: None

RETURNS DESCRIPTION
str

A string representing the encoded and signed JWT.

Source code in authx/schema.py
def encode(
    self,
    key: str,
    algorithm: AlgorithmType = "HS256",
    ignore_errors: bool = True,
    headers: Optional[dict[str, Any]] = None,
    data: Optional[dict[str, Any]] = None,
) -> str:
    """Generate a JSON Web Token (JWT) with the current payload's claims and configuration.

    Creates a signed token using the specified cryptographic key and algorithm, incorporating all token metadata.

    Args:
        key: The cryptographic key used for token signing.
        algorithm: The cryptographic algorithm for token signing. Defaults to HS256.
        ignore_errors: Flag to suppress potential encoding errors. Defaults to True.
        headers: Optional custom headers to include in the token.
        data: Optional additional data to embed in the token.

    Returns:
        A string representing the encoded and signed JWT.
    """
    return create_token(
        key=key,
        algorithm=algorithm,
        uid=str(self.sub),
        jti=self.jti,
        issued=self.iat,
        # TODO: Fix type hinting for `type` Field
        # it's caused because Type is a string & what we expect is a TokenType
        # TokenType = Literal["access", "refresh"]
        # Investigate if it's possible to fix this
        type=self.type,  # type: ignore
        expiry=self.exp,
        fresh=self.fresh,
        csrf=self.csrf,
        audience=self.aud,
        issuer=self.iss,
        not_before=self.nbf,
        ignore_errors=ignore_errors,
        headers=headers,
        data=data,
    )

decode classmethod #

decode(token, key, algorithms=None, audience=None, issuer=None, verify=True)

Decode and validate a JSON Web Token (JWT) into a TokenPayload instance.

Converts a signed token into a structured payload object, with optional verification and validation parameters.

PARAMETER DESCRIPTION
token

TYPE: str

key

TYPE: str

algorithms

TYPE: Optional[Sequence[AlgorithmType]] DEFAULT: None

audience

TYPE: Optional[StringOrSequence] DEFAULT: None

issuer

TYPE: Optional[str] DEFAULT: None

verify

TYPE: bool DEFAULT: True

PARAMETER DESCRIPTION
token

The encoded JWT string to be decoded.

TYPE: str

key

The cryptographic key used for token verification.

TYPE: str

algorithms

Optional list of allowed cryptographic algorithms. Defaults to HS256.

TYPE: Optional[Sequence[AlgorithmType]] DEFAULT: None

audience

Optional expected token audience.

TYPE: Optional[StringOrSequence] DEFAULT: None

issuer

Optional expected token issuer.

TYPE: Optional[str] DEFAULT: None

verify

Flag to enable or disable token verification. Defaults to True.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
TokenPayload

A TokenPayload instance representing the decoded token's claims.

Source code in authx/schema.py
@classmethod
def decode(
    cls,
    token: str,
    key: str,
    algorithms: Optional[Sequence[AlgorithmType]] = None,
    audience: Optional[StringOrSequence] = None,
    issuer: Optional[str] = None,
    verify: bool = True,
) -> "TokenPayload":
    """Decode and validate a JSON Web Token (JWT) into a TokenPayload instance.

    Converts a signed token into a structured payload object, with optional verification and validation parameters.

    Args:
        token: The encoded JWT string to be decoded.
        key: The cryptographic key used for token verification.
        algorithms: Optional list of allowed cryptographic algorithms. Defaults to HS256.
        audience: Optional expected token audience.
        issuer: Optional expected token issuer.
        verify: Flag to enable or disable token verification. Defaults to True.

    Returns:
        A TokenPayload instance representing the decoded token's claims.
    """
    if algorithms is None:  # pragma: no cover
        algorithms = ["HS256"]  # pragma: no cover
    payload = decode_token(
        token=token,
        key=key,
        algorithms=algorithms,
        audience=audience,
        issuer=issuer,
        verify=verify,
    )
    return cls.model_validate(payload) if PYDANTIC_V2 else cls(**payload)