JWT Utilities¶
- encode_jwt(payload: dict[str, Any], key_obj: OKPKey = <joserfc._rfc8037.okp_key.OKPKey object>, algorithm: str = 'Ed25519', expire_minutes: int = 30, expire_timedelta: timedelta | None = None) str[source]¶
Encode a JWT based on the provided payload and expiration settings.
This function adds standard claims: iat (issued at), exp (expiration), and jti (JWT ID) to the token payload before encoding.
- Parameters:
payload (dict) – The base data to include in the token (e.g., user ID, email).
key_obj (OKPKey) – The private key used for signing the token. Defaults to the application’s configured private key.
algorithm (str) – The cryptographic algorithm used for signing (e.g., ‘Ed25519’). Defaults to the configured algorithm.
expire_minutes (int) – The token’s lifespan in minutes, used only if expire_timedelta is not provided.
expire_timedelta (timedelta | None) – Explicit timedelta defining the token’s total lifespan. Overrides expire_minutes. Used primarily for Refresh Tokens.
- Returns:
The encoded JWT string.
- Return type:
- decode_jwt(token: str | bytes, key_obj: OKPKey = <joserfc._rfc8037.okp_key.OKPKey object>, algorithm: str = 'Ed25519') Token[source]¶
Decode and validate a JWT using the application’s key.
This function automatically verifies the token’s signature and standard claims (such as expiration time).
- Parameters:
token (str | bytes) – The encoded JWT string or bytes to be decoded.
key_obj (OKPKey) – The key used for verifying the token’s signature. Defaults to the application’s configured key.
algorithm (str) – The cryptographic algorithm used for verification (e.g., ‘Ed25519’). Defaults to the configured algorithm.
- Returns:
The extracted token object, which contains header and claims.
- Return type:
Token
- Raises:
joserfc.errors.BadSignatureError – If the token signature verification fails.
joserfc.errors.InvalidPayloadError – If the token’s payload is not a valid JSON object.