### Install Litestar Auth Dependencies Source: https://github.com/zylvext/litestar-auth/blob/main/docs/quickstart.md Install the necessary library and an asynchronous SQLite driver to get started with the authentication framework. ```bash uv add litestar-auth aiosqlite ``` -------------------------------- ### Quick Peek Example in Python Source: https://github.com/zylvext/litestar-auth/blob/main/docs/index.md This snippet provides a quick overview of how to set up Litestar Auth in a basic application. It demonstrates the plugin entry point and basic configuration, serving as an introductory example for new users. ```python from litestar import Litestar from litestar_auth.contrib.redis import RedisAuthCredentialsManager from litestar_auth.plugins import LitestarAuth app = Litestar([ LitestarAuth( # Use Redis for session storage auth_credentials_manager=RedisAuthCredentialsManager(redis_url="redis://localhost:6379"), # Use JWT for authentication tokens token_strategy="jwt", ) ]) ``` -------------------------------- ### Install Litestar Auth dependencies Source: https://context7.com/zylvext/litestar-auth/llms.txt Commands to install the core library and optional feature sets including Redis, OAuth, and TOTP support. ```bash pip install litestar-auth pip install litestar-auth[all] pip install litestar-auth[redis] pip install litestar-auth[oauth] pip install litestar-auth[totp] ``` -------------------------------- ### Named Authentication Backends Example (Python) Source: https://github.com/zylvext/litestar-auth/blob/main/docs/concepts/backends.md Demonstrates how to explicitly name multiple `AuthenticationBackend` instances when more than one is used. This is crucial for managing distinct authentication flows and ensuring that their associated paths do not collide. ```python AuthenticationBackend(name="api", transport=BearerTransport(), strategy=jwt_strategy) AuthenticationBackend(name="mobile", transport=BearerTransport(), strategy=db_strategy) ``` -------------------------------- ### OAuth2 Social Login HTTP Endpoints Source: https://context7.com/zylvext/litestar-auth/llms.txt Provides example cURL commands for initiating OAuth2 login flows and handling provider callbacks. It covers starting the authorization process and the automatic handling of the callback to obtain tokens or create sessions. ```bash # OAuth HTTP endpoints # Start OAuth login (redirects to provider) curl -X GET "http://localhost:8000/auth/oauth/google/authorize?redirect_uri=https://app.example.com/callback" # Browser redirects to Google OAuth consent screen # Provider callback (handled automatically) # GET /auth/oauth/google/callback?code=...&state=... # Returns access token or creates user session # Account linking (authenticated user) curl -X GET "http://localhost:8000/auth/associate/github/authorize" \ -H "Authorization: Bearer eyJ..." # Starts linking flow for logged-in user ``` -------------------------------- ### Configure Litestar Auth Plugin Source: https://github.com/zylvext/litestar-auth/blob/main/docs/quickstart.md Initialize the LitestarAuthConfig, instantiate the LitestarAuth plugin, and register it with the Litestar application. This setup assumes the use of the default SQLAlchemy user model. ```python from litestar import Litestar from litestar_auth import LitestarAuth, LitestarAuthConfig auth_config = LitestarAuthConfig(...) auth_plugin = LitestarAuth(config=auth_config) app = Litestar(plugins=[auth_plugin]) ``` -------------------------------- ### Cookie Transport with CSRF Protection Setup Source: https://context7.com/zylvext/litestar-auth/llms.txt Illustrates the setup for using cookie transport for session management, which includes automatic Cross-Site Request Forgery (CSRF) protection. This is essential for secure browser-based applications. ```python from litestar_auth import ( LitestarAuthConfig, AuthenticationBackend, CookieTransport, JWTStrategy, ) ``` -------------------------------- ### Define Authentication Backends Source: https://context7.com/zylvext/litestar-auth/llms.txt Imports and setup for various transport and strategy components, including Cookie/Bearer transports and JWT/Redis/Database token strategies. ```python from datetime import timedelta from uuid import UUID from litestar_auth import ( AuthenticationBackend, BearerTransport, CookieTransport, JWTStrategy, DatabaseTokenStrategy, RedisTokenStrategy, RedisJWTDenylistStore, AccessToken, RefreshToken, ) ``` -------------------------------- ### Interact with Authentication API Endpoints Source: https://context7.com/zylvext/litestar-auth/llms.txt Provides curl examples for common authentication tasks including user registration, login, token refresh, logout, email verification, and password reset. ```bash curl -X POST http://localhost:8000/auth/register -H "Content-Type: application/json" -d '{"email": "user@example.com", "password": "securepassword123"}' curl -X POST http://localhost:8000/auth/login -H "Content-Type: application/json" -d '{"identifier": "user@example.com", "password": "securepassword123"}' curl -X GET http://localhost:8000/users/me -H "Authorization: Bearer eyJ..." curl -X POST http://localhost:8000/auth/logout -H "Authorization: Bearer eyJ..." curl -X POST http://localhost:8000/auth/refresh -H "Content-Type: application/json" -d '{"refresh_token": "..."}' curl -X POST http://localhost:8000/auth/verify -H "Content-Type: application/json" -d '{"token": "verification-token-from-email"}' curl -X POST http://localhost:8000/auth/request-verify-token -H "Content-Type: application/json" -d '{"email": "user@example.com"}' curl -X POST http://localhost:8000/auth/forgot-password -H "Content-Type: application/json" -d '{"email": "user@example.com"}' curl -X POST http://localhost:8000/auth/reset-password -H "Content-Type: application/json" -d '{"token": "reset-token", "password": "newpassword123"}' ``` -------------------------------- ### Configure LitestarAuth Plugin Source: https://context7.com/zylvext/litestar-auth/llms.txt Setup the LitestarAuth plugin with a custom user manager, SQLAlchemy database integration, and JWT authentication strategy. This configuration registers necessary middleware and routes for user lifecycle management. ```python from datetime import timedelta from uuid import UUID from litestar import Litestar from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine from litestar_auth import BaseUserManager, LitestarAuth, LitestarAuthConfig, PasswordHelper, SQLAlchemyUserDatabase from litestar_auth.authentication.backend import AuthenticationBackend from litestar_auth.authentication.strategy import JWTStrategy from litestar_auth.authentication.transport import BearerTransport from litestar_auth.models import User DATABASE_URL = "sqlite+aiosqlite:///./auth.db" engine = create_async_engine(DATABASE_URL, echo=False) session_maker = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) class UserManager(BaseUserManager[User, UUID]): async def on_after_register(self, user: User, token: str) -> None: print(f"User {user.email} registered. Verification token: {token}") async def on_after_forgot_password(self, user: User | None, token: str | None) -> None: if user and token: print(f"Password reset requested for {user.email}") def build_app() -> Litestar: jwt_strategy = JWTStrategy[User, UUID]( secret="replace-with-32+-char-jwt-secret-key", lifetime=timedelta(minutes=15), subject_decoder=UUID, issuer="my-app", ) backend = AuthenticationBackend[User, UUID]( name="jwt", transport=BearerTransport(), strategy=jwt_strategy, ) config = LitestarAuthConfig( backends=(backend,), session_maker=session_maker, user_model=User, user_manager_class=UserManager, user_db_factory=lambda session: SQLAlchemyUserDatabase(session, user_model=User), user_manager_kwargs={ "password_helper": PasswordHelper(), "verification_token_secret": "replace-with-32+-char-verify-secret", "reset_password_token_secret": "replace-with-32+-char-reset-secret", }, include_register=True, include_verify=True, include_reset_password=True, include_users=True, enable_refresh=False, auth_path="/auth", users_path="/users", ) return Litestar(plugins=[LitestarAuth(config)]) app = build_app() ``` -------------------------------- ### Configure Cookie Authentication and CSRF Source: https://context7.com/zylvext/litestar-auth/llms.txt Sets up a secure cookie transport with JWT strategy and CSRF protection. Includes examples for interacting with the authentication endpoints using curl. ```python cookie_transport = CookieTransport( cookie_name="auth_token", cookie_secure=True, cookie_httponly=True, cookie_samesite="lax", cookie_max_age=3600, refresh_cookie_name="refresh_token", ) backend = AuthenticationBackend( name="cookie", transport=cookie_transport, strategy=JWTStrategy(secret="your-secret", lifetime=timedelta(hours=1)), ) config = LitestarAuthConfig( backends=(backend,), session_maker=session_maker, user_model=User, user_manager_class=UserManager, csrf_secret="32+-char-csrf-secret-for-cookie-auth", csrf_header_name="X-CSRF-Token", ) ``` ```bash # Login sets HttpOnly cookie automatically curl -X POST http://localhost:8000/auth/login \ -H "Content-Type: application/json" \ -d '{"identifier": "user@example.com", "password": "password"}' \ -c cookies.txt # Subsequent requests must include CSRF token for state-changing methods curl -X POST http://localhost:8000/auth/logout \ -H "X-CSRF-Token: csrf-token-from-cookie" \ -b cookies.txt ``` -------------------------------- ### GET /users/me Source: https://context7.com/zylvext/litestar-auth/llms.txt Retrieves the profile of the currently authenticated user. ```APIDOC ## GET /users/me ### Description Returns the profile information for the authenticated user. ### Method GET ### Endpoint /users/me ### Parameters #### Headers - **Authorization** (string) - Required - Bearer token ### Response #### Success Response (200) - **id** (uuid) - User ID - **email** (string) - User email ``` -------------------------------- ### Configure Authentication Backends Source: https://context7.com/zylvext/litestar-auth/llms.txt Demonstrates how to initialize different authentication backends including JWT with Redis denylist, database-backed sessions, and Redis-based token storage. ```python jwt_backend = AuthenticationBackend[User, UUID]( name="api", transport=BearerTransport(), strategy=JWTStrategy( secret="your-jwt-signing-secret-32chars+", lifetime=timedelta(minutes=15), subject_decoder=UUID, issuer="my-app", denylist_store=RedisJWTDenylistStore(redis=redis_client), ), ) db_backend = AuthenticationBackend[User, UUID]( name="session", transport=CookieTransport( cookie_name="auth_token", cookie_secure=True, cookie_httponly=True, cookie_samesite="lax", ), strategy=DatabaseTokenStrategy( access_token_model=AccessToken, refresh_token_model=RefreshToken, access_token_lifetime=timedelta(hours=1), refresh_token_lifetime=timedelta(days=7), ), ) redis_backend = AuthenticationBackend[User, UUID]( name="redis", transport=BearerTransport(), strategy=RedisTokenStrategy( redis=redis_client, access_token_lifetime=timedelta(hours=1), key_prefix="auth:token:", ), ) ``` -------------------------------- ### Run Release-Quality Verification with uv Source: https://github.com/zylvext/litestar-auth/blob/main/docs/contributing.md Executes a suite of quality assurance tools including linting, formatting, type checking, dependency auditing, and unit testing. This command ensures the codebase meets project standards before submission. ```bash uv run ruff check --fix . uv run ruff format . uv run ty check uv run deptry . uv run pytest ``` -------------------------------- ### POST /auth/2fa/enable Source: https://github.com/zylvext/litestar-auth/blob/main/docs/guides/totp.md Initiates the TOTP enrollment process by returning a secret and an otpauth URI. ```APIDOC ## POST /auth/2fa/enable ### Description Initiates the TOTP enrollment process. Returns a secret, an otpauth URI, and a short-lived enrollment_token. Requires the current password for step-up authentication. ### Method POST ### Endpoint /auth/2fa/enable ### Request Body - **password** (string) - Required - The user's current password for step-up authentication. ### Response #### Success Response (200) - **secret** (string) - The TOTP secret key. - **otpauth_uri** (string) - The URI for QR code generation. - **enrollment_token** (string) - A short-lived JWT for confirmation. ``` -------------------------------- ### Importing Core Authentication Components Source: https://github.com/zylvext/litestar-auth/blob/main/docs/api/package.md Demonstrates the recommended way to import essential authentication classes and utilities from the litestar_auth package. This ensures access to stable symbols for configuring authentication backends, strategies, and user management. ```python from litestar_auth import ( LitestarAuth, LitestarAuthConfig, AuthenticationBackend, JWTStrategy, BearerTransport, BaseUserManager, User, SQLAlchemyUserDatabase, ) ``` -------------------------------- ### POST /auth/register Source: https://context7.com/zylvext/litestar-auth/llms.txt Registers a new user in the system. ```APIDOC ## POST /auth/register ### Description Creates a new user account. ### Method POST ### Endpoint /auth/register ### Request Body - **email** (string) - Required - User email address - **password** (string) - Required - User password ### Request Example { "email": "user@example.com", "password": "securepassword123" } ### Response #### Success Response (200) - **id** (uuid) - User ID - **email** (string) - User email - **is_active** (boolean) - Activation status ``` -------------------------------- ### AuthenticationBackend Configuration Source: https://github.com/zylvext/litestar-auth/blob/main/docs/concepts/backends.md Defines the structure and configuration of an AuthenticationBackend, including how to handle multiple backends. ```APIDOC ## AuthenticationBackend Configuration ### Description An `AuthenticationBackend` is composed of a name, a transport, and a strategy. The middleware processes backends in the order they are defined, with the first successful match determining the user. ### Parameters - **name** (string) - Required - Unique identifier for the backend. - **transport** (Transport) - Required - Mechanism to extract tokens from requests (e.g., BearerTransport, CookieTransport). - **strategy** (Strategy) - Required - Logic to interpret and persist tokens (e.g., JWTStrategy, DatabaseTokenStrategy, RedisTokenStrategy). ### Request Example ```python AuthenticationBackend( name="api", transport=BearerTransport(), strategy=jwt_strategy ) ``` ### Routing Behavior - **Primary Backend**: The first backend is exposed at the configured `auth_path` (default `/auth`). - **Additional Backends**: Mounted under `/auth/{backend-name}/` to prevent path collisions. ``` -------------------------------- ### Redis Contrib Overview Source: https://github.com/zylvext/litestar-auth/blob/main/docs/api/contrib_redis.md Documentation for the Redis-backed helpers provided by the litestar-auth[redis] extra. ```APIDOC ## Redis Contrib ### Description Provides optional Redis-backed storage helpers for authentication sessions or tokens. Requires the `litestar-auth[redis]` dependency to be installed. ### Usage Ensure your environment has the redis extra installed: `pip install litestar-auth[redis]` ### Configuration - **RedisStore**: Use this class to interface with Redis for session management. - **Dependencies**: Requires a running Redis instance and the `redis` python client. ``` -------------------------------- ### Implement Route Guards Source: https://context7.com/zylvext/litestar-auth/llms.txt Shows how to secure Litestar routes using built-in guards like is_authenticated, is_active, is_verified, and is_superuser to restrict access based on user state. ```python from litestar import Litestar, get, post from litestar_auth import is_authenticated, is_active, is_verified, is_superuser from litestar_auth.models import User @get("/public") async def public_endpoint() -> dict: return {"message": "Hello, world!"} @get("/profile", guards=[is_authenticated]) async def get_profile(request_user: User) -> dict: return {"email": request_user.email} @get("/dashboard", guards=[is_active]) async def get_dashboard(request_user: User) -> dict: return {"email": request_user.email, "active": request_user.is_active} @get("/verified-only", guards=[is_verified]) async def verified_content(request_user: User) -> dict: return {"verified": True} @get("/admin", guards=[is_superuser]) async def admin_panel(request_user: User) -> dict: return {"admin": True, "user": request_user.email} @post("/admin/users/{user_id:uuid}", guards=[is_superuser]) async def update_user(user_id: UUID, data: dict) -> dict: return {"updated": str(user_id)} ``` -------------------------------- ### Extend User Model and Define Schemas Source: https://context7.com/zylvext/litestar-auth/llms.txt Demonstrates how to extend the base Litestar user model using SQLAlchemy and define custom msgspec schemas for data validation and serialization. ```python class User(BaseUser): __tablename__ = "user" username: Mapped[str | None] = mapped_column(String(50), unique=True, nullable=True) display_name: Mapped[str | None] = mapped_column(String(100), nullable=True) avatar_url: Mapped[str | None] = mapped_column(String(500), nullable=True) class CustomUserRead(msgspec.Struct): id: UUID email: str username: str | None display_name: str | None avatar_url: str | None is_active: bool is_verified: bool ``` -------------------------------- ### Configuring and Managing TOTP Two-Factor Authentication Source: https://context7.com/zylvext/litestar-auth/llms.txt Configure TOTP settings including replay protection and step-up authentication. This snippet also demonstrates manual TOTP operations like secret generation, URI creation, and code verification. ```python from litestar_auth import LitestarAuthConfig, TotpConfig, RedisUsedTotpCodeStore, generate_totp_secret, generate_totp_uri, verify_totp totp_config = TotpConfig( totp_pending_secret="32+-char-secret-for-pending-2fa-jwt", totp_issuer="MyApp", totp_algorithm="SHA256", totp_used_tokens_store=RedisUsedTotpCodeStore(redis=redis_client), totp_require_replay_protection=True, totp_enable_requires_password=True ) secret = generate_totp_secret(algorithm="SHA256") uri = generate_totp_uri(secret=secret, email="user@example.com", issuer="MyApp", algorithm="SHA256") is_valid = verify_totp(secret, "123456", algorithm="SHA256") ``` ```bash curl -X POST http://localhost:8000/auth/2fa/enable \ -H "Authorization: Bearer eyJ..." \ -H "Content-Type: application/json" \ -d '{"password": "current-password"}' ``` -------------------------------- ### POST /auth/login Source: https://context7.com/zylvext/litestar-auth/llms.txt Authenticates a user and returns an access token. ```APIDOC ## POST /auth/login ### Description Authenticates user credentials and returns a bearer token. ### Method POST ### Endpoint /auth/login ### Request Body - **identifier** (string) - Required - User email - **password** (string) - Required - User password ### Request Example { "identifier": "user@example.com", "password": "securepassword123" } ### Response #### Success Response (200) - **access_token** (string) - JWT token - **token_type** (string) - Token type (e.g., bearer) ``` -------------------------------- ### User Registration API Source: https://github.com/zylvext/litestar-auth/blob/main/docs/guides/registration.md Handles user registration. When enabled, clients can call POST {auth_path}/register. Registration uses safe creation, accepting only expected fields like email and password. ```APIDOC ## POST /register ### Description Allows new users to register an account. The `login_identifier` setting determines whether email or username is used for lookup. Registration is secured to prevent the inclusion of privileged fields like `is_superuser`. ### Method POST ### Endpoint `{auth_path}/register` ### Parameters #### Request Body - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's desired password. - **username** (string) - Optional - The user's desired username (if `login_identifier` is set to 'username'). ### Request Example ```json { "email": "user@example.com", "password": "securepassword123", "username": "newuser" } ``` ### Response #### Success Response (201 Created) - **message** (string) - Indicates successful registration. #### Response Example ```json { "message": "User registered successfully" } ``` ``` -------------------------------- ### POST /auth/2fa/verify Source: https://github.com/zylvext/litestar-auth/blob/main/docs/guides/totp.md Verifies the second factor during the login process. ```APIDOC ## POST /auth/2fa/verify ### Description Completes the login process when a second factor is required. ### Method POST ### Endpoint /auth/2fa/verify ### Request Body - **pending_token** (string) - Required - The JWT representing the pending login state. - **code** (string) - Required - The TOTP code provided by the user. ``` -------------------------------- ### User Registration and Verification Source: https://github.com/zylvext/litestar-auth/blob/main/docs/http_api.md Endpoints for user account creation and email verification workflows. ```APIDOC ## POST {auth}/register ### Description Registers a new user account and triggers verification hooks. ### Method POST ### Endpoint {auth}/register ### Request Body - **email** (string) - Required - User email address. - **password** (string) - Required - User password. ## POST {auth}/verify ### Description Confirms user email address using a verification token. ### Method POST ### Endpoint {auth}/verify ### Parameters #### Query Parameters - **token** (string) - Required - The verification token sent to the user. ``` -------------------------------- ### Litestar Auth Plugin Configuration Source: https://github.com/zylvext/litestar-auth/blob/main/docs/api/plugin.md Details on the public plugin facade and configuration structures used to initialize authentication in Litestar applications. ```APIDOC ## Configuration and Plugin Facade ### Description This section covers the `litestar_auth.plugin` and `litestar_auth.config` modules, which provide the necessary dataclasses and helpers to configure authentication providers and plugins within a Litestar application. ### Usage Import the `AuthPlugin` or relevant configuration dataclasses to define your authentication strategy. ### Configuration Parameters - **config** (dataclass) - Required - The configuration object defining authentication settings such as session backends, user models, and token expiration. ### Example ```python from litestar_auth.plugin import AuthPlugin from litestar_auth.config import AuthConfig config = AuthConfig(...) plugin = AuthPlugin(config=config) ``` ``` -------------------------------- ### POST /auth/2fa/enable/confirm Source: https://github.com/zylvext/litestar-auth/blob/main/docs/guides/totp.md Confirms the TOTP enrollment by validating the provided code against the enrollment token. ```APIDOC ## POST /auth/2fa/enable/confirm ### Description Finalizes the enrollment process by verifying the TOTP code provided by the user. ### Method POST ### Endpoint /auth/2fa/enable/confirm ### Request Body - **enrollment_token** (string) - Required - The token received from the enable endpoint. - **code** (string) - Required - The TOTP code generated by the authenticator app. ``` -------------------------------- ### Rate Limiting Configuration for Auth Endpoints Source: https://context7.com/zylvext/litestar-auth/llms.txt Configures rate limiting for authentication endpoints to prevent brute-force attacks. It demonstrates using Redis for production and in-memory limiters for development, with different scopes and namespaces for various actions. ```python from litestar_auth import ( LitestarAuthConfig, AuthRateLimitConfig, EndpointRateLimit, InMemoryRateLimiter, RedisRateLimiter, ) # Production: Redis-backed rate limiter (shared across workers) rate_limiter = RedisRateLimiter( redis=redis_client, max_attempts=5, window_seconds=300, # 5 attempts per 5 minutes ) # Development: In-memory rate limiter (single process only) dev_limiter = InMemoryRateLimiter( max_attempts=10, window_seconds=60, ) rate_limit_config = AuthRateLimitConfig( login=EndpointRateLimit( backend=rate_limiter, scope="ip_email", # Rate limit by IP + email combination namespace="login", trusted_proxy=True, # Only if behind trusted reverse proxy ), register=EndpointRateLimit( backend=rate_limiter, scope="ip", namespace="register", ), forgot_password=EndpointRateLimit( backend=rate_limiter, scope="ip_email", namespace="forgot_password", ), reset_password=EndpointRateLimit( backend=rate_limiter, scope="ip", namespace="reset_password", ), totp_verify=EndpointRateLimit( backend=rate_limiter, scope="ip_email", namespace="totp_verify", ), ) config = LitestarAuthConfig( backends=(backend,), session_maker=session_maker, user_model=User, user_manager_class=UserManager, rate_limit_config=rate_limit_config, # ... other config ) ``` -------------------------------- ### Implementing Custom User Manager Lifecycle Hooks in Python Source: https://context7.com/zylvext/litestar-auth/llms.txt Subclass BaseUserManager to define custom logic for user registration, login, password management, and deletion. This allows for integration with external services like email providers and audit logging systems. ```python from uuid import UUID from litestar_auth import BaseUserManager from litestar_auth.models import User class UserManager(BaseUserManager[User, UUID]): async def on_after_register(self, user: User, token: str) -> None: await email_service.send_verification(to=user.email, verification_link=f"https://app.example.com/verify?token={token}") await audit_log.record("user_registered", user_id=str(user.id)) async def on_after_login(self, user: User) -> None: await audit_log.record("user_login", user_id=str(user.id)) async def on_after_verify(self, user: User) -> None: await email_service.send_welcome(to=user.email) async def on_after_request_verify_token(self, user: User, token: str) -> None: await email_service.send_verification(to=user.email, verification_link=f"https://app.example.com/verify?token={token}") async def on_after_forgot_password(self, user: User | None, token: str | None) -> None: if user and token: await email_service.send_password_reset(to=user.email, reset_link=f"https://app.example.com/reset?token={token}") else: await asyncio.sleep(0.1) async def on_after_reset_password(self, user: User) -> None: await email_service.send_password_changed_notification(to=user.email) async def on_after_update(self, user: User, update_dict: dict) -> None: await audit_log.record("user_updated", user_id=str(user.id), changes=update_dict) async def on_before_delete(self, user: User) -> None: if await has_active_subscriptions(user.id): raise ValueError("Cannot delete user with active subscriptions") async def on_after_delete(self, user: User) -> None: await cleanup_user_data(user.id) await audit_log.record("user_deleted", user_id=str(user.id)) ``` -------------------------------- ### Typical Error Response Structure Source: https://github.com/zylvext/litestar-auth/blob/main/docs/errors.md Illustrates the common JSON structure for authentication-related errors, including a machine-readable `code` in the `extra` field. ```APIDOC ## Typical Error Response Structure ### Description Authentication-related HTTP errors use Litestar `ClientException` (or guard failures) with a machine-readable **`code`** in `extra` where the library controls the response. Clients should rely on **`code`**, not only on `detail` text. ### Response Example ```json { "status_code": 400, "detail": "Human-readable message", "extra": { "code": "LOGIN_BAD_CREDENTIALS" } } ``` ### Note Exact JSON layout follows your Litestar exception handler configuration. ``` -------------------------------- ### OAuth2 Social Login Configuration Source: https://context7.com/zylvext/litestar-auth/llms.txt Configures OAuth2 providers like Google and GitHub for social login. It sets up clients, defines the OAuth configuration, and enables optional account linking for authenticated users. ```python from httpx_oauth.clients.google import GoogleOAuth2 from httpx_oauth.clients.github import GitHubOAuth2 from litestar_auth import LitestarAuthConfig, OAuthConfig # Create OAuth clients google_client = GoogleOAuth2( client_id="your-google-client-id", client_secret="your-google-client-secret", ) github_client = GitHubOAuth2( client_id="your-github-client-id", client_secret="your-github-client-secret", ) oauth_config = OAuthConfig( oauth_providers=[ ("google", google_client), ("github", github_client), ], oauth_cookie_secure=True, # Required in production: encrypt OAuth tokens at rest oauth_token_encryption_key="32-byte-fernet-key-base64-encoded", # Account linking for logged-in users include_oauth_associate=True, oauth_associate_providers=[ ("google", google_client), ("github", github_client), ], oauth_associate_by_email=False, # Safer: require explicit linking ) config = LitestarAuthConfig( backends=(backend,), session_maker=session_maker, user_model=User, user_manager_class=UserManager, oauth_config=oauth_config, # ... other config ) ``` -------------------------------- ### Authentication Core Endpoints Source: https://github.com/zylvext/litestar-auth/blob/main/docs/http_api.md Endpoints for managing user sessions and token lifecycle. ```APIDOC ## POST {auth}/login ### Description Authenticates a user and returns tokens or establishes a session. ### Method POST ### Endpoint {auth}/login ### Request Body - **credentials** (object) - Required - User login credentials (e.g., email/password). ### Response #### Success Response (200) - **token** (string) - Access token or session identifier. ## POST {auth}/logout ### Description Invalidates the current session or token. ### Method POST ### Endpoint {auth}/logout ### Response #### Success Response (200) - **message** (string) - Confirmation of logout. ``` -------------------------------- ### User Management (CRUD) Source: https://github.com/zylvext/litestar-auth/blob/main/docs/http_api.md Endpoints for managing user profiles and administrative user operations. ```APIDOC ## GET {users}/me ### Description Retrieves the profile of the currently authenticated user. ### Method GET ### Endpoint {users}/me ### Response #### Success Response (200) - **user** (object) - The authenticated user profile object. ## PATCH {users}/{id} ### Description Updates a user profile (Requires superuser privileges). ### Method PATCH ### Endpoint {users}/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user. ``` -------------------------------- ### Rate Limiting Configuration Source: https://context7.com/zylvext/litestar-auth/llms.txt Configuration options for applying rate limiting to authentication endpoints to prevent abuse. ```APIDOC ## Rate Limiting Configuration ### Description This section details how to configure rate limiting for various authentication endpoints using `LitestarAuthConfig` and `AuthRateLimitConfig`. Rate limiting helps protect against brute-force attacks. ### Key Components - **`AuthRateLimitConfig`**: A class to define rate limiting rules for different authentication operations (login, register, etc.). - **`EndpointRateLimit`**: Defines the rate limiter, scope, namespace, and other settings for a specific endpoint. - **`InMemoryRateLimiter`**: A simple in-memory rate limiter suitable for development environments. - **`RedisRateLimiter`**: A rate limiter that uses Redis, suitable for production environments requiring shared state across multiple processes or servers. ### Example Configuration ```python from litestar_auth import ( LitestarAuthConfig, AuthRateLimitConfig, EndpointRateLimit, InMemoryRateLimiter, RedisRateLimiter ) import redis # Assuming redis client is configured elsewhere # Production: Redis-backed rate limiter redis_client = redis.Redis(host='localhost', port=6379, db=0) rate_limiter = RedisRateLimiter( redis=redis_client, max_attempts=5, window_seconds=300 # 5 attempts per 5 minutes ) # Development: In-memory rate limiter dev_limiter = InMemoryRateLimiter( max_attempts=10, window_seconds=60 # 10 attempts per minute ) rate_limit_config = AuthRateLimitConfig( login=EndpointRateLimit( backend=rate_limiter, # Use redis rate limiter for login scope="ip_email", # Rate limit by IP address and email namespace="login", trusted_proxy=True # Set to True if behind a trusted reverse proxy ), register=EndpointRateLimit( backend=dev_limiter, # Use in-memory limiter for registration in dev scope="ip", # Rate limit by IP address only namespace="register" ), forgot_password=EndpointRateLimit( backend=rate_limiter, scope="ip_email", namespace="forgot_password" ), reset_password=EndpointRateLimit( backend=rate_limiter, scope="ip", namespace="reset_password" ), totp_verify=EndpointRateLimit( backend=rate_limiter, scope="ip_email", namespace="totp_verify" ) ) # Integrate into LitestarAuthConfig config = LitestarAuthConfig( # ... other auth config rate_limit_config=rate_limit_config ) ``` ### Rate Limiting Parameters - **`backend`**: An instance of a rate limiter (e.g., `RedisRateLimiter`, `InMemoryRateLimiter`). - **`scope`**: Defines the criteria for rate limiting (e.g., 'ip', 'ip_email', 'user_id'). - **`namespace`**: A string to uniquely identify the rate limit context. - **`trusted_proxy`**: Boolean, set to `True` if the application is behind a trusted reverse proxy to correctly identify client IPs. ``` -------------------------------- ### TOTP Enrollment and Verification Source: https://context7.com/zylvext/litestar-auth/llms.txt Handles the enrollment and confirmation of Time-based One-Time Password (TOTP) for two-factor authentication. It includes steps for enabling, confirming, verifying, and disabling TOTP using API calls. ```bash curl -X POST http://localhost:8000/auth/2fa/enable/confirm \ -H "Authorization: Bearer eyJ..." \ -H "Content-Type: application/json" \ -d '{"enrollment_token": "...", "code": "123456"}' ``` ```bash curl -X POST http://localhost:8000/auth/login \ -H "Content-Type: application/json" \ -d '{"identifier": "user@example.com", "password": "password"}' ``` ```bash curl -X POST http://localhost:8000/auth/2fa/verify \ -H "Content-Type: application/json" \ -d '{"pending_token": "...", "code": "123456"}' ``` ```bash curl -X POST http://localhost:8000/auth/2fa/disable \ -H "Authorization: Bearer eyJ..." \ -H "Content-Type: application/json" \ -d '{"code": "123456"}' ```