Token Service
Relevant source files
The following files were used as context for generating this wiki page:
The Token Service is a core component of the FLEXT Auth architecture responsible for the centralized management of the JWT (JSON Web Token) lifecycle. It provides high-level operations for creating, validating, refreshing, and revoking tokens, ensuring robust security across the enterprise authentication service. The service is built using Python 3.13+ features and adheres to Railway-Oriented Programming (ROP) principles to handle complex logic flows and error states gracefully.
Sources: src/flext_auth/services/token_service.py:1-13, README.md
Within the FLEXT Auth ecosystem, the Token Service acts as a mediator between application-level authentication requests and low-level provider implementations. It utilizes lazy caching for JWT providers to optimize performance and incorporates audit logging for all critical token events, such as generation and validation failures.
Sources: src/flext_auth/services/token_service.py:28-40, src/flext_auth/services/token_service.py:117-127
Service Architecture and Components
The FlextAuthTokenService is composed of several key dependencies injected during initialization, including settings, a provider service, and a dispatcher. It leverages FlextAuthUtilitiesManagers to access user-specific operations required for token payload construction.
Class Structure
The following class diagram illustrates the internal structure and dependencies of the Token Service:
Key Components
| Component | Description |
|---|---|
provider_service | Fetches the specific JWT provider implementation used for signing and verifying tokens. |
user_manager | Handles user lookup to ensure identities exist before issuing tokens. |
jwt_provider_cache | A lazy-loaded cache that stores the provider to eliminate repeated lookups. |
Result[T] | A wrapper type used for ROP, representing either a success (ok) or a failure (fail). |
Sources: src/flext_auth/services/token_service.py:41-47, src/flext_auth/services/token_service.py:117-127
Token Lifecycle Operations
Token Generation
Token generation involves looking up the user, dumping user data (excluding sensitive credentials), and delegating the cryptographic signing to the cached JWT provider. The system supports multiple token kinds, with access as the default.
Token Validation
Validation is a streamlined process that passes a token string to the provider. The service uses the tap_error pattern to log validation failures without breaking the result chain.
def validate_token(self, token: str) -> p.Result[bool]:
"""Railway-oriented token validation with audit logging."""
def _log_token_validation_error(error: str) -> None:
u.fetch_logger(__name__).debug(
"Token validation",
success=False,
token_id=self._short_token(token),
reason=error or "Unknown error",
)
return (
self
._get_jwt_provider_cached()
.flat_map(lambda provider: provider.validate(token))
.tap_error(_log_token_validation_error)
)
Sources: src/flext_auth/services/token_service.py:129-145
Token Refresh
The refresh operation takes an existing token and uses the provider to issue a new AuthToken model. This model includes the new token string, identity ID, and expiration timestamp.
Sources: src/flext_auth/services/token_service.py:100-127
Domain Constants and Configuration
The Token Service relies on constants defined in the FlextAuthConstants namespace for default behaviors and validation limits.
| Constant | Default Value | Description |
|---|---|---|
DEFAULT_JWT_EXPIRY_MINUTES | 1440 | Default expiry for tokens if not specified. |
DEFAULT_JWT_ALGORITHM | "HS256" | Default HMAC algorithm for signing. |
TokenTypes.ACCESS | "access" | Standard token type for authorization. |
TokenTypes.REFRESH | "refresh" | Token type used for obtaining new access tokens. |
Sources: src/flext_auth/history.json:constants.py:118-128, src/flext_auth/history.json:constants.py:82-90
Testing and Quality Assurance
The service is validated through a comprehensive testing suite that ensures high coverage and reliability.
- Unit Tests: Focus on the
FlextAuthTokenServicelogic using mocked providers to ensure correct result handling and logging. - Integration Tests: Validate the interaction between the Token Service and real cryptographic providers (e.g.,
PyJWT). - Performance Tests: Benchmark token generation and validation speeds, targeting response times under 100ms for unit-level operations.
Sources: tests/unit/README.md:92-101, tests/README.md:65-80
The project uses pyjwt and cryptography as primary underlying libraries for these operations, as specified in the project dependencies.
Sources: pyproject.toml:25-31
Conclusion
The Token Service provides a secure, abstracted interface for token management within FLEXT Auth. By utilizing Railway-Oriented Programming and lazy-loaded providers, it ensures that token operations are both performant and resilient to failure, forming the backbone of the system's stateless authentication mechanism.
Sources: src/flext_auth/services/token_service.py:1-13, examples/basic_refactored_usage_06.py:133-145