Skip to content

Plugin and configuration

Public plugin facade and configuration dataclasses exported from litestar_auth.plugin, plus shared configuration helpers from litestar_auth.config.

litestar_auth.plugin

Litestar plugin/orchestrator facade for wiring the auth library into an app.

LitestarAuth(config)

Bases: InitPlugin

Main auth orchestrator that wires middleware, controllers, and DI.

Store the plugin configuration and validate the requested setup.

Parameters:

Name Type Description Default
config LitestarAuthConfig[UP, ID]

Fully specified plugin configuration (session factory, backends, user manager factory, optional OAuth/TOTP settings).

required
Source code in litestar_auth/plugin.py
def __init__(self, config: LitestarAuthConfig[UP, ID]) -> None:
    """Store the plugin configuration and validate the requested setup.

    Args:
        config: Fully specified plugin configuration (session factory, backends,
            user manager factory, optional OAuth/TOTP settings).
    """
    self.config = config
    oauth_token_encryption_key = (
        self.config.oauth_config.oauth_token_encryption_key if self.config.oauth_config is not None else None
    )
    register_oauth_token_encryption_key(self, oauth_token_encryption_key)
    validate_config(self.config)
    self._session_maker = _plugin_config.require_session_maker(self.config)
    self._user_manager_factory = _plugin_config.resolve_user_manager_factory(self.config)
    self._provide_user_manager = _make_user_manager_dependency_provider(
        self._build_user_manager,
        self.config.db_session_dependency_key,
    )
    self._provide_request_backends = _make_backends_dependency_provider(
        self._session_bound_backends,
        self.config.db_session_dependency_key,
    )
    self._provide_oauth_associate_user_manager = _make_user_manager_dependency_provider(
        self._build_user_manager,
        self.config.db_session_dependency_key,
    )

on_app_init(app_config)

Register auth middleware, controllers, and dependencies on the app.

Returns:

Type Description
AppConfig

The updated application config.

Source code in litestar_auth/plugin.py
@override
def on_app_init(self, app_config: AppConfig) -> AppConfig:
    """Register auth middleware, controllers, and dependencies on the app.

    Returns:
        The updated application config.
    """
    warn_insecure_plugin_startup_defaults(self.config)
    require_oauth_token_encryption_for_configured_providers(
        config=self.config,
        require_key=partial(require_oauth_token_encryption_key, self),
    )
    warn_if_insecure_oauth_redirect_in_production(config=self.config, app_config=app_config)
    self._register_dependencies(app_config)
    self._register_middleware(app_config)
    self._register_controllers(app_config)
    self._register_exception_handlers(app_config)
    return app_config

litestar_auth.config

Central configuration helpers for litestar-auth.

This module contains small, shared primitives used across the library to keep security-relevant validation consistent (e.g. secret length requirements and testing-mode toggles).

is_pytest_runtime()

Return whether current process is executing under pytest.

Source code in litestar_auth/config.py
def is_pytest_runtime() -> bool:
    """Return whether current process is executing under pytest."""
    return os.getenv("PYTEST_CURRENT_TEST") is not None

is_testing()

Return whether litestar-auth is running in testing mode.

Source code in litestar_auth/config.py
def is_testing() -> bool:
    """Return whether litestar-auth is running in testing mode."""
    return os.getenv("LITESTAR_AUTH_TESTING", "0") == "1"

require_password_length(password, minimum_length=DEFAULT_MINIMUM_PASSWORD_LENGTH, *, maximum_length=MAX_PASSWORD_LENGTH)

Raise when a password falls outside the configured length bounds.

The default minimum_length matches the password-length metadata exposed for app-owned user schemas via litestar_auth.schemas.UserPasswordField.

Raises:

Type Description
ValueError

If password exceeds maximum_length or is shorter than minimum_length.

Source code in litestar_auth/config.py
def require_password_length(
    password: str,
    minimum_length: int = DEFAULT_MINIMUM_PASSWORD_LENGTH,
    *,
    maximum_length: int = MAX_PASSWORD_LENGTH,
) -> None:
    """Raise when a password falls outside the configured length bounds.

    The default ``minimum_length`` matches the password-length metadata exposed
    for app-owned user schemas via ``litestar_auth.schemas.UserPasswordField``.

    Raises:
        ValueError: If ``password`` exceeds ``maximum_length`` or is shorter
            than ``minimum_length``.
    """
    if len(password) > maximum_length:
        msg = f"Password must be at most {maximum_length} characters long."
        raise ValueError(msg)

    if len(password) < minimum_length:
        msg = f"Password must be at least {minimum_length} characters long."
        raise ValueError(msg)

resolve_trusted_proxy_setting(*, trusted_proxy)

Validate and normalize trusted-proxy configuration flags.

Parameters:

Name Type Description Default
trusted_proxy object

Candidate trusted-proxy value from configuration.

required

Returns:

Type Description
bool

Normalized trusted-proxy boolean.

Raises:

Type Description
ConfigurationError

If trusted_proxy is not a boolean value.

Source code in litestar_auth/config.py
def resolve_trusted_proxy_setting(*, trusted_proxy: object) -> bool:
    """Validate and normalize trusted-proxy configuration flags.

    Args:
        trusted_proxy: Candidate trusted-proxy value from configuration.

    Returns:
        Normalized trusted-proxy boolean.

    Raises:
        ConfigurationError: If ``trusted_proxy`` is not a boolean value.
    """
    if isinstance(trusted_proxy, bool):
        return trusted_proxy

    msg = "trusted_proxy must be a boolean."
    raise ConfigurationError(msg)

validate_secret_length(secret, *, label, minimum_length=MINIMUM_SECRET_LENGTH)

Validate the configured secret length.

Parameters:

Name Type Description Default
secret str

Secret value to validate.

required
label str

Human-readable label used in error messages.

required
minimum_length int

Minimum length in characters.

MINIMUM_SECRET_LENGTH

Raises:

Type Description
ConfigurationError

When secret is shorter than minimum_length.

Source code in litestar_auth/config.py
def validate_secret_length(secret: str, *, label: str, minimum_length: int = MINIMUM_SECRET_LENGTH) -> None:
    """Validate the configured secret length.

    Args:
        secret: Secret value to validate.
        label: Human-readable label used in error messages.
        minimum_length: Minimum length in characters.

    Raises:
        ConfigurationError: When ``secret`` is shorter than ``minimum_length``.
    """
    if len(secret) >= minimum_length:
        return

    msg = f"{label} must be at least {minimum_length} characters."
    raise ConfigurationError(msg)

validate_testing_mode_for_startup()

Fail fast when testing mode is enabled outside pytest runtimes.

Raises:

Type Description
ConfigurationError

When LITESTAR_AUTH_TESTING=1 is active in a non-test runtime.

Source code in litestar_auth/config.py
def validate_testing_mode_for_startup() -> None:
    """Fail fast when testing mode is enabled outside pytest runtimes.

    Raises:
        ConfigurationError: When ``LITESTAR_AUTH_TESTING=1`` is active in a non-test runtime.
    """
    if not is_testing() or is_pytest_runtime():
        return

    msg = (
        "LITESTAR_AUTH_TESTING=1 is intended for automated tests only and cannot be enabled "
        "for non-test runtime startup."
    )
    raise ConfigurationError(msg)