API Reference

Complete API documentation for litestar-oauth.

Core Types

OAuthUserInfo

class litestar_oauth.types.OAuthUserInfo[source]

Bases: object

User information retrieved from an OAuth provider.

provider

Name of the OAuth provider (e.g., ‘google’, ‘github’).

oauth_id

Unique identifier from the OAuth provider.

email

User’s email address, if available.

email_verified

Whether the email has been verified by the provider.

username

User’s username, if available.

first_name

User’s first name, if available.

last_name

User’s last name, if available.

avatar_url

URL to the user’s avatar image, if available.

profile_url

URL to the user’s profile page, if available.

raw_data

Complete raw response data from the provider.

Parameters:
provider: str
oauth_id: str
email: str | None
email_verified: bool
username: str | None
first_name: str | None
last_name: str | None
avatar_url: str | None
profile_url: str | None
raw_data: dict[str, Any]
property full_name: str | None

Construct full name from first and last name components.

Returns:

Combined full name if either component exists, None otherwise.

__init__(*, provider, oauth_id, email=None, email_verified=False, username=None, first_name=None, last_name=None, avatar_url=None, profile_url=None, raw_data=<factory>)
Parameters:

OAuthToken

class litestar_oauth.types.OAuthToken[source]

Bases: object

OAuth2 access token and associated metadata.

access_token

The OAuth2 access token.

token_type

Type of token (typically ‘Bearer’).

expires_in

Token lifetime in seconds, if provided.

refresh_token

Refresh token for obtaining new access tokens, if available.

scope

Space-separated list of granted scopes, if provided.

id_token

OpenID Connect ID token, if provided.

raw_response

Complete raw token response from the provider.

Parameters:
access_token: str
token_type: str
expires_in: int | None
refresh_token: str | None
scope: str | None
id_token: str | None
raw_response: dict[str, Any]
property expires_at: datetime | None

Calculate absolute expiration timestamp.

Returns:

UTC timestamp when the token expires, or None if expires_in not set.

__init__(*, access_token, token_type='Bearer', expires_in=None, refresh_token=None, scope=None, id_token=None, raw_response=<factory>)
Parameters:

OAuthState

class litestar_oauth.types.OAuthState[source]

Bases: object

State parameter for OAuth2 authorization flow security.

The state parameter prevents CSRF attacks by verifying that authorization callbacks originate from requests initiated by this application.

state

Random state string for CSRF protection.

provider

Name of the OAuth provider.

redirect_uri

URI where the provider should redirect after authorization.

created_at

UTC timestamp when the state was created.

next_url

Optional URL to redirect to after successful authentication.

extra_data

Additional application-specific data to preserve across the flow.

Parameters:
state: str
provider: str
redirect_uri: str
created_at: datetime
next_url: str | None
extra_data: dict[str, Any]
__init__(*, state, provider, redirect_uri, created_at=<factory>, next_url=None, extra_data=<factory>)
Parameters:

Service

OAuthService

class litestar_oauth.service.OAuthService[source]

Bases: object

Central service for OAuth2 provider management and operations.

This service manages multiple OAuth providers, handles state management for security, and provides a unified API for OAuth operations.

providers

Registry of configured OAuth providers.

state_manager

Manager for OAuth state tokens.

Parameters:
__init__(providers=None, state_manager=None)[source]

Initialize the OAuth service.

Parameters:
  • providers (Mapping[str, OAuthProvider] | None) – Optional mapping of provider names to provider instances.

  • state_manager (OAuthStateManager | None) – Optional custom state manager. If not provided, uses default.

register(provider)[source]

Register an OAuth provider with the service.

Parameters:

provider (OAuthProvider) – Provider instance to register.

Raises:

ValueError – If a provider with the same name is already registered.

Return type:

None

get_provider(provider_name)[source]

Retrieve a registered OAuth provider.

Parameters:

provider_name (str) – Name of the provider to retrieve.

Return type:

OAuthProvider

Returns:

The requested OAuth provider instance.

Raises:

ProviderNotConfiguredError – If the provider is not registered.

list_providers()[source]

Get names of all registered providers.

Return type:

list[str]

Returns:

List of provider names currently registered.

async get_authorization_url(provider_name, redirect_uri, next_url=None, extra_data=None, **kwargs)[source]

Generate an authorization URL for a provider.

This is the first step in the OAuth flow. The generated URL includes a secure state parameter for CSRF protection.

Parameters:
  • provider_name (str) – Name of the OAuth provider to use.

  • redirect_uri (str) – URI where the provider should redirect after authorization.

  • next_url (str | None) – Optional URL to redirect to after successful authentication.

  • extra_data (dict[str, Any] | None) – Optional additional data to preserve across the OAuth flow.

  • **kwargs (Any) – Additional provider-specific parameters.

Return type:

str

Returns:

Complete authorization URL to redirect the user to.

Raises:

ProviderNotConfiguredError – If the provider is not available.

classmethod from_config(providers_config, provider_classes, state_ttl=600)[source]

Create an OAuthService from configuration dictionaries.

This factory method simplifies service setup when configuration comes from files, environment variables, or other sources.

Parameters:
  • providers_config (Mapping[str, Mapping[str, Any]]) – Mapping of provider names to their configuration. Each config should include ‘client_id’, ‘client_secret’, and optional ‘scope’.

  • provider_classes (Mapping[str, type[OAuthProvider]]) – Mapping of provider names to their implementation classes.

  • state_ttl (int) – Time-to-live for state tokens in seconds.

Return type:

OAuthService

Returns:

Configured OAuthService instance.

Example:

from litestar_oauth.providers import GoogleProvider, GitHubProvider

config = {
    "google": {
        "client_id": "your-client-id",
        "client_secret": "your-secret",
        "scope": ["openid", "email", "profile"],
    },
    "github": {
        "client_id": "your-client-id",
        "client_secret": "your-secret",
    },
}

classes = {
    "google": GoogleProvider,
    "github": GitHubProvider,
}

service = OAuthService.from_config(config, classes)

OAuthStateManager

class litestar_oauth.service.OAuthStateManager[source]

Bases: object

In-memory state manager for OAuth2 CSRF protection.

This manager generates, stores, and validates state tokens used in OAuth flows to prevent CSRF attacks. States are stored in memory with a TTL.

default_ttl

Default time-to-live for state tokens in seconds.

Parameters:

default_ttl (int)

__init__(default_ttl=600)[source]

Initialize the state manager.

Parameters:

default_ttl (int) – Default lifetime for state tokens in seconds. Defaults to 600 (10 minutes).

generate_state(provider, redirect_uri, next_url=None, extra_data=None, ttl=None)[source]

Generate a new OAuth state token.

Parameters:
  • provider (str) – Name of the OAuth provider.

  • redirect_uri (str) – URI for OAuth callback.

  • next_url (str | None) – Optional URL to redirect to after authentication.

  • extra_data (dict[str, Any] | None) – Optional additional data to store with state.

  • ttl (int | None) – Optional custom TTL for this state in seconds.

Return type:

OAuthState

Returns:

Generated OAuth state object.

validate_state(state, provider=None)[source]

Validate and retrieve an OAuth state.

Parameters:
  • state (str) – State string to validate.

  • provider (str | None) – Optional provider name to verify against.

Return type:

OAuthState

Returns:

The validated OAuth state object.

Raises:
  • InvalidStateError – If state is not found or provider doesn’t match.

  • ExpiredStateError – If state has exceeded its TTL.

consume_state(state, provider=None)[source]

Validate and remove an OAuth state (one-time use).

Parameters:
  • state (str) – State string to consume.

  • provider (str | None) – Optional provider name to verify against.

Return type:

OAuthState

Returns:

The validated OAuth state object.

Raises:
  • InvalidStateError – If state is not found or provider doesn’t match.

  • ExpiredStateError – If state has exceeded its TTL.

cleanup_expired()[source]

Remove all expired states from storage.

Return type:

int

Returns:

Number of expired states removed.

clear()[source]

Remove all states from storage.

This is primarily useful for testing or application shutdown.

Return type:

None

Base Classes

BaseOAuthProvider

class litestar_oauth.base.BaseOAuthProvider[source]

Bases: ABC

Abstract base class providing common OAuth2 provider functionality.

This class implements shared logic for OAuth providers, reducing duplication and ensuring consistent behavior. Concrete providers should inherit from this class and implement the abstract methods.

client_id

OAuth2 client identifier.

client_secret

OAuth2 client secret.

_scope

List of OAuth scopes to request.

Parameters:
__init__(client_id, client_secret, scope=None)[source]

Initialize the OAuth provider with credentials.

Parameters:
  • client_id (str) – OAuth2 client identifier from the provider.

  • client_secret (str) – OAuth2 client secret from the provider.

  • scope (list[str] | None) – List of OAuth scopes to request. Defaults to provider-specific scopes.

abstract property provider_name: str

Unique identifier for this provider.

abstract property authorize_url: str

Provider’s authorization endpoint URL.

abstract property token_url: str

Provider’s token endpoint URL.

abstract property user_info_url: str

Provider’s user info endpoint URL.

property scope: list[str]

List of OAuth scopes to request.

is_configured()[source]

Check if the provider has required configuration.

Return type:

bool

Returns:

True if client_id and client_secret are set.

async get_authorization_url(redirect_uri, state, **kwargs)[source]

Generate authorization URL.

Parameters:
  • redirect_uri (str) – Callback URI for the OAuth flow.

  • state (str) – CSRF protection state parameter.

  • **kwargs (Any) – Provider-specific parameters (e.g., scope, extra_params).

Return type:

str

Returns:

Complete authorization URL.

async exchange_code(code, redirect_uri, **kwargs)[source]

Exchange authorization code for access token.

Parameters:
  • code (str) – Authorization code from provider.

  • redirect_uri (str) – Redirect URI used in authorization.

  • **kwargs (Any) – Provider-specific parameters.

Return type:

OAuthToken

Returns:

OAuth token with access token and metadata.

Raises:

TokenExchangeError – If exchange fails.

async refresh_token(refresh_token, **kwargs)[source]

Refresh an access token.

Parameters:
  • refresh_token (str) – Refresh token from previous response.

  • **kwargs (Any) – Provider-specific parameters.

Return type:

OAuthToken

Returns:

New OAuth token.

Raises:

TokenRefreshError – If refresh fails.

abstractmethod async get_user_info(access_token, **kwargs)[source]

Fetch user information.

Parameters:
  • access_token (str) – Valid access token.

  • **kwargs (Any) – Provider-specific parameters.

Return type:

OAuthUserInfo

Returns:

User information from provider.

Raises:

UserInfoError – If fetching fails.

async revoke_token(token, token_type_hint=None, **kwargs)[source]

Revoke a token.

Default implementation returns False. Providers should override if they support token revocation.

Parameters:
  • token (str) – Token to revoke.

  • token_type_hint (str | None) – Type of token being revoked.

  • **kwargs (Any) – Provider-specific parameters.

Return type:

bool

Returns:

True if revocation succeeded.

OAuthProvider

class litestar_oauth.base.OAuthProvider[source]

Bases: Protocol

Protocol defining the interface for OAuth2 providers.

All OAuth providers must implement this interface to be compatible with the OAuthService. This protocol ensures type safety and consistent behavior.

property provider_name: str

Unique identifier for this provider (e.g., ‘google’, ‘github’).

property authorize_url: str

URL where users are redirected to authorize the application.

property token_url: str

URL for exchanging authorization codes for access tokens.

property user_info_url: str

URL for retrieving user profile information.

property scope: list[str]

List of OAuth scopes requested from the provider.

is_configured()[source]

Check if the provider has all required configuration.

Return type:

bool

Returns:

True if the provider is properly configured and ready to use.

async get_authorization_url(redirect_uri, state, **kwargs)[source]

Generate the URL to redirect users for authorization.

Parameters:
  • redirect_uri (str) – URI where the provider should redirect after authorization.

  • state (str) – CSRF protection state parameter.

  • **kwargs (Any) – Additional provider-specific parameters.

Return type:

str

Returns:

Complete authorization URL with all required parameters.

async exchange_code(code, redirect_uri, **kwargs)[source]

Exchange an authorization code for an access token.

Parameters:
  • code (str) – Authorization code received from the provider.

  • redirect_uri (str) – Redirect URI used in the authorization request.

  • **kwargs (Any) – Additional provider-specific parameters.

Return type:

OAuthToken

Returns:

OAuth token containing access token and metadata.

Raises:

TokenExchangeError – If the code exchange fails.

async refresh_token(refresh_token, **kwargs)[source]

Use a refresh token to obtain a new access token.

Parameters:
  • refresh_token (str) – The refresh token from a previous token response.

  • **kwargs (Any) – Additional provider-specific parameters.

Return type:

OAuthToken

Returns:

New OAuth token with fresh access token.

Raises:

TokenRefreshError – If token refresh fails.

async get_user_info(access_token, **kwargs)[source]

Retrieve user information using an access token.

Parameters:
  • access_token (str) – Valid access token from the provider.

  • **kwargs (Any) – Additional provider-specific parameters.

Return type:

OAuthUserInfo

Returns:

Structured user information from the provider.

Raises:

UserInfoError – If fetching user info fails.

async revoke_token(token, token_type_hint=None, **kwargs)[source]

Revoke an access or refresh token.

Parameters:
  • token (str) – The token to revoke.

  • token_type_hint (str | None) – Optional hint about token type (‘access_token’ or ‘refresh_token’).

  • **kwargs (Any) – Additional provider-specific parameters.

Return type:

bool

Returns:

True if revocation succeeded, False otherwise.

__init__(*args, **kwargs)

Providers

GitHubOAuthProvider

class litestar_oauth.providers.github.GitHubOAuthProvider[source]

Bases: BaseOAuthProvider

GitHub OAuth2 provider.

Implements OAuth2 authentication flow for GitHub.

Default scopes:
  • read:user: Read user profile data

  • user:email: Access user email addresses

User Info Mapping:
  • oauth_id: GitHub user ID

  • email: Primary email (requires separate API call if not public)

  • username: GitHub login

  • first_name: Extracted from name field

  • last_name: Extracted from name field

  • avatar_url: GitHub avatar URL

  • profile_url: GitHub profile URL

Parameters:
  • client_id (str) – GitHub OAuth App client ID.

  • client_secret (str) – GitHub OAuth App client secret.

  • scope (list[str] | None) – Optional custom scopes. Defaults to [“read:user”, “user:email”].

property provider_name: str

Return provider identifier.

Returns:

Provider name ‘github’.

property authorize_url: str

Return GitHub authorization endpoint.

Returns:

GitHub OAuth authorization URL.

property token_url: str

Return GitHub token exchange endpoint.

Returns:

GitHub OAuth token URL.

property user_info_url: str

Return GitHub user info endpoint.

Returns:

GitHub API user endpoint URL.

async get_user_info(access_token, **kwargs)[source]

Fetch and normalize GitHub user information.

Retrieves user profile from GitHub API and normalizes it to OAuthUserInfo format. If the primary email is not public, makes an additional API call to fetch it.

Parameters:
  • access_token (str) – GitHub OAuth access token.

  • kwargs (Any)

Return type:

OAuthUserInfo

Returns:

Normalized user information.

Raises:

GoogleOAuthProvider

class litestar_oauth.providers.google.GoogleOAuthProvider[source]

Bases: BaseOAuthProvider

Google OAuth2 provider with OpenID Connect support.

Implements OAuth2 authentication flow for Google accounts. Supports OpenID Connect (OIDC) for enhanced authentication.

Default scopes:
  • openid: Required for OIDC

  • email: Access user email

  • profile: Access user profile info

User Info Mapping:
  • oauth_id: Google user ID (sub claim)

  • email: User email address

  • email_verified: Email verification status

  • username: Not provided by Google (uses email)

  • first_name: Given name

  • last_name: Family name

  • avatar_url: Profile picture URL

  • profile_url: Not provided by Google

Parameters:
  • client_id (str) – Google OAuth client ID.

  • client_secret (str) – Google OAuth client secret.

  • scope (list[str] | None) – Optional custom scopes. Defaults to [“openid”, “email”, “profile”].

property provider_name: str

Return provider identifier.

Returns:

Provider name ‘google’.

property authorize_url: str

Return Google authorization endpoint.

Returns:

Google OAuth authorization URL.

property token_url: str

Return Google token exchange endpoint.

Returns:

Google OAuth token URL.

property user_info_url: str

Return Google user info endpoint.

Returns:

Google UserInfo endpoint URL.

async get_user_info(access_token, **kwargs)[source]

Fetch and normalize Google user information.

Retrieves user profile from Google UserInfo endpoint and normalizes it to OAuthUserInfo format. If an id_token is available from the token response, it can be used to verify claims.

Parameters:
  • access_token (str) – Google OAuth access token.

  • kwargs (Any)

Return type:

OAuthUserInfo

Returns:

Normalized user information.

Raises:

DiscordOAuthProvider

class litestar_oauth.providers.discord.DiscordOAuthProvider[source]

Bases: BaseOAuthProvider

Discord OAuth2 provider.

Implements OAuth2 authentication flow for Discord.

Default scopes:
  • identify: Access basic user information

  • email: Access user email address

User Info Mapping:
  • oauth_id: Discord user ID (snowflake)

  • email: User email address

  • email_verified: Email verification status

  • username: Discord username (with discriminator if applicable)

  • first_name: Discord username (no first/last name separation)

  • last_name: Empty (Discord doesn’t separate names)

  • avatar_url: Discord CDN avatar URL

  • profile_url: Not provided by Discord

Parameters:
  • client_id (str) – Discord OAuth application client ID.

  • client_secret (str) – Discord OAuth application client secret.

  • scope (list[str] | None) – Optional custom scopes. Defaults to [“identify”, “email”].

property provider_name: str

Return provider identifier.

Returns:

Provider name ‘discord’.

property authorize_url: str

Return Discord authorization endpoint.

Returns:

Discord OAuth authorization URL.

property token_url: str

Return Discord token exchange endpoint.

Returns:

Discord OAuth token URL.

property user_info_url: str

Return Discord user info endpoint.

Returns:

Discord API user endpoint URL.

async get_user_info(access_token, **kwargs)[source]

Fetch and normalize Discord user information.

Retrieves user profile from Discord API and normalizes it to OAuthUserInfo format. Handles Discord’s avatar hash and CDN URL construction.

Parameters:
  • access_token (str) – Discord OAuth access token.

  • **kwargs (Any) – Additional parameters (unused).

Return type:

OAuthUserInfo

Returns:

Normalized user information.

Raises:

GenericOAuthProvider

class litestar_oauth.providers.generic.GenericOAuthProvider[source]

Bases: BaseOAuthProvider

Generic OAuth2/OIDC provider.

Configurable provider that can work with any OAuth2 or OpenID Connect compliant identity provider. Supports OIDC discovery for automatic endpoint configuration.

This provider is useful for integrating with custom OAuth providers or providers not explicitly supported by dedicated provider classes.

Parameters:
  • client_id (str) – OAuth client ID.

  • client_secret (str) – OAuth client secret.

  • authorize_url (str) – Authorization endpoint URL.

  • token_url (str) – Token endpoint URL.

  • user_info_url (str) – UserInfo endpoint URL.

  • provider_name (str) – Unique identifier for this provider instance.

  • scope (list[str] | None) – List of OAuth scopes. Defaults to [“openid”, “email”, “profile”].

  • discovery_url (str | None) – Optional OIDC discovery URL (.well-known/openid-configuration). If provided, endpoints will be discovered automatically.

  • user_id_field (str) – Field name in user info response containing the user ID. Defaults to “sub” (OIDC standard).

  • email_field (str) – Field name for email. Defaults to “email”.

  • email_verified_field (str) – Field name for email verification. Defaults to “email_verified”.

  • username_field (str) – Field name for username. Defaults to “preferred_username”.

  • first_name_field (str) – Field name for first name. Defaults to “given_name”.

  • last_name_field (str) – Field name for last name. Defaults to “family_name”.

  • avatar_url_field (str) – Field name for avatar URL. Defaults to “picture”.

  • profile_url_field (str) – Field name for profile URL. Defaults to “profile”.

Example:

# Keycloak provider
provider = GenericOAuthProvider(
    client_id="my-client",
    client_secret="secret",
    authorize_url="https://keycloak.example.com/realms/myrealm/protocol/openid-connect/auth",
    token_url="https://keycloak.example.com/realms/myrealm/protocol/openid-connect/token",
    user_info_url="https://keycloak.example.com/realms/myrealm/protocol/openid-connect/userinfo",
    provider_name="keycloak",
    scope=["openid", "email", "profile"],
)

# Or using OIDC discovery
provider = GenericOAuthProvider(
    client_id="my-client",
    client_secret="secret",
    provider_name="keycloak",
    discovery_url="https://keycloak.example.com/realms/myrealm/.well-known/openid-configuration",
)
__init__(client_id, client_secret, authorize_url='', token_url='', user_info_url='', provider_name='generic', scope=None, discovery_url=None, user_id_field='sub', email_field='email', email_verified_field='email_verified', username_field='preferred_username', first_name_field='given_name', last_name_field='family_name', avatar_url_field='picture', profile_url_field='profile')[source]

Initialize the generic OAuth provider.

Parameters:
  • client_id (str) – OAuth client ID.

  • client_secret (str) – OAuth client secret.

  • authorize_url (str) – Authorization endpoint URL.

  • token_url (str) – Token endpoint URL.

  • user_info_url (str) – UserInfo endpoint URL.

  • provider_name (str) – Unique provider identifier.

  • scope (list[str] | None) – List of OAuth scopes.

  • discovery_url (str | None) – Optional OIDC discovery URL.

  • user_id_field (str) – User ID field name.

  • email_field (str) – Email field name.

  • email_verified_field (str) – Email verified field name.

  • username_field (str) – Username field name.

  • first_name_field (str) – First name field name.

  • last_name_field (str) – Last name field name.

  • avatar_url_field (str) – Avatar URL field name.

  • profile_url_field (str) – Profile URL field name.

property provider_name: str

Return provider identifier.

Returns:

Provider name.

property authorize_url: str

Return authorization endpoint URL.

Returns:

Authorization URL (may be discovered via OIDC).

property token_url: str

Return token endpoint URL.

Returns:

Token URL (may be discovered via OIDC).

property user_info_url: str

Return user info endpoint URL.

Returns:

UserInfo URL (may be discovered via OIDC).

async discover_configuration()[source]

Discover OAuth/OIDC configuration from discovery URL.

Fetches the .well-known/openid-configuration endpoint and caches the configuration for endpoint discovery.

Raises:
Return type:

None

async get_user_info(access_token, **kwargs)[source]

Fetch and normalize user information.

Retrieves user profile from the configured user info endpoint and normalizes it using the configured field mappings.

Parameters:
  • access_token (str) – OAuth access token.

  • **kwargs (Any) – Additional parameters (unused).

Return type:

OAuthUserInfo

Returns:

Normalized user information.

Raises:

Exceptions

Exception hierarchy for OAuth2 operations.

This module defines all custom exceptions that can be raised during OAuth2 authentication flows, providing clear error handling and debugging information.

exception litestar_oauth.exceptions.ExpiredStateError[source]

Bases: StateValidationError

Raised when the OAuth state has exceeded its time-to-live.

State tokens have a limited lifetime to reduce attack windows. This error indicates the authorization flow took too long to complete.

exception litestar_oauth.exceptions.InvalidStateError[source]

Bases: StateValidationError

Raised when the OAuth state parameter is invalid or doesn’t match.

This security-critical error indicates a potential CSRF attack or application error. Causes include: - State parameter missing from callback - State doesn’t match any stored state - State has been tampered with

exception litestar_oauth.exceptions.OAuthError[source]

Bases: Exception

Base exception for all OAuth2-related errors.

All custom exceptions in this library inherit from this base class, allowing consumers to catch all OAuth errors with a single handler.

exception litestar_oauth.exceptions.ProviderNotConfiguredError[source]

Bases: OAuthError

Raised when attempting to use an OAuth provider that hasn’t been configured.

This typically occurs when a provider is referenced but was never registered with the OAuthService, or when required configuration (client ID, secret) is missing.

exception litestar_oauth.exceptions.StateValidationError[source]

Bases: OAuthError

Base exception for OAuth state validation errors.

State validation is critical for preventing CSRF attacks. This base class is subclassed for specific state-related errors.

exception litestar_oauth.exceptions.TokenExchangeError[source]

Bases: OAuthError

Raised when the authorization code to token exchange fails.

This error occurs during the OAuth2 callback phase when exchanging the authorization code for an access token. Common causes include: - Invalid or expired authorization code - Incorrect client credentials - Mismatched redirect URI - Network or provider errors

exception litestar_oauth.exceptions.TokenRefreshError[source]

Bases: OAuthError

Raised when token refresh fails.

This error occurs when attempting to use a refresh token to obtain a new access token. Common causes include: - Invalid or expired refresh token - Revoked refresh token - Provider policy changes - Network or provider errors

exception litestar_oauth.exceptions.UserInfoError[source]

Bases: OAuthError

Raised when fetching user information from the provider fails.

This error occurs when the provider’s user info endpoint returns an error or unexpected response. Common causes include: - Invalid or expired access token - Insufficient scope permissions - Provider API changes - Network or provider errors

Litestar Integration

OAuthConfig

class litestar_oauth.contrib.litestar.config.OAuthConfig[source]

Bases: object

Configuration for the Litestar OAuth plugin.

This configuration class allows you to set up OAuth providers and customize the behavior of the OAuth authentication flow.

redirect_base_url

Base URL for OAuth callbacks (e.g., “https://example.com”)

route_prefix

URL prefix for OAuth routes (default: “/auth”)

success_redirect

URL to redirect to after successful authentication (default: “/dashboard”)

failure_redirect

URL to redirect to after failed authentication (default: “/login?error=oauth”)

state_ttl

Time-to-live for OAuth state tokens in seconds (default: 600)

enabled_providers

List of provider names to enable. If None, all configured providers are enabled.

github_client_id

GitHub OAuth client ID

github_client_secret

GitHub OAuth client secret

github_scope

GitHub OAuth scopes (default: “user:email”)

google_client_id

Google OAuth client ID

google_client_secret

Google OAuth client secret

google_scope

Google OAuth scopes (default: “openid email profile”)

discord_client_id

Discord OAuth client ID

discord_client_secret

Discord OAuth client secret

discord_scope

Discord OAuth scopes (default: “identify email”)

microsoft_client_id

Microsoft OAuth client ID

microsoft_client_secret

Microsoft OAuth client secret

microsoft_tenant_id

Microsoft tenant ID (default: “common”)

microsoft_scope

Microsoft OAuth scopes (default: “openid email profile”)

apple_client_id

Apple Sign In client ID

apple_team_id

Apple team ID

apple_key_id

Apple key ID

apple_private_key

Apple private key for JWT signing

apple_scope

Apple OAuth scopes (default: “name email”)

gitlab_client_id

GitLab OAuth client ID

gitlab_client_secret

GitLab OAuth client secret

gitlab_url

GitLab instance URL (default: “https://gitlab.com”)

gitlab_scope

GitLab OAuth scopes (default: “read_user”)

twitter_client_id

Twitter/X OAuth client ID

twitter_client_secret

Twitter/X OAuth client secret

twitter_scope

Twitter OAuth scopes (default: “users.read tweet.read”)

facebook_client_id

Facebook OAuth client ID

facebook_client_secret

Facebook OAuth client secret

facebook_scope

Facebook OAuth scopes (default: “email public_profile”)

linkedin_client_id

LinkedIn OAuth client ID

linkedin_client_secret

LinkedIn OAuth client secret

linkedin_scope

LinkedIn OAuth scopes (default: “openid email profile”)

bitbucket_client_id

Bitbucket OAuth client ID

bitbucket_client_secret

Bitbucket OAuth client secret

bitbucket_scope

Bitbucket OAuth scopes (default: “account email”)

Example:

from litestar import Litestar
from litestar_oauth.contrib.litestar import OAuthPlugin, OAuthConfig

app = Litestar(
    plugins=[
        OAuthPlugin(
            config=OAuthConfig(
                redirect_base_url="https://example.com",
                github_client_id="your-client-id",
                github_client_secret="your-client-secret",
                google_client_id="your-client-id",
                google_client_secret="your-client-secret",
                enabled_providers=["github", "google"],
            )
        )
    ],
)
Parameters:
  • redirect_base_url (str)

  • route_prefix (str)

  • success_redirect (str)

  • failure_redirect (str)

  • state_ttl (int)

  • enabled_providers (Sequence[str] | None)

  • github_client_id (str | None)

  • github_client_secret (str | None)

  • github_scope (str)

  • google_client_id (str | None)

  • google_client_secret (str | None)

  • google_scope (str)

  • discord_client_id (str | None)

  • discord_client_secret (str | None)

  • discord_scope (str)

  • microsoft_client_id (str | None)

  • microsoft_client_secret (str | None)

  • microsoft_tenant_id (str)

  • microsoft_scope (str)

  • apple_client_id (str | None)

  • apple_team_id (str | None)

  • apple_key_id (str | None)

  • apple_private_key (str | None)

  • apple_scope (str)

  • gitlab_client_id (str | None)

  • gitlab_client_secret (str | None)

  • gitlab_url (str)

  • gitlab_scope (str)

  • twitter_client_id (str | None)

  • twitter_client_secret (str | None)

  • twitter_scope (str)

  • facebook_client_id (str | None)

  • facebook_client_secret (str | None)

  • facebook_scope (str)

  • linkedin_client_id (str | None)

  • linkedin_client_secret (str | None)

  • linkedin_scope (str)

  • bitbucket_client_id (str | None)

  • bitbucket_client_secret (str | None)

  • bitbucket_scope (str)

redirect_base_url: str
route_prefix: str = '/auth'
success_redirect: str = '/dashboard'
failure_redirect: str = '/login?error=oauth'
state_ttl: int = 600
enabled_providers: Sequence[str] | None = None
github_client_id: str | None = None
github_client_secret: str | None = None
github_scope: str = 'user:email'
google_client_id: str | None = None
google_client_secret: str | None = None
google_scope: str = 'openid email profile'
discord_client_id: str | None = None
discord_client_secret: str | None = None
discord_scope: str = 'identify email'
microsoft_client_id: str | None = None
microsoft_client_secret: str | None = None
microsoft_tenant_id: str = 'common'
microsoft_scope: str = 'openid email profile'
apple_client_id: str | None = None
apple_team_id: str | None = None
apple_key_id: str | None = None
apple_private_key: str | None = None
apple_scope: str = 'name email'
gitlab_client_id: str | None = None
gitlab_client_secret: str | None = None
gitlab_url: str = 'https://gitlab.com'
gitlab_scope: str = 'read_user'
twitter_client_id: str | None = None
twitter_client_secret: str | None = None
twitter_scope: str = 'users.read tweet.read'
facebook_client_id: str | None = None
facebook_client_secret: str | None = None
facebook_scope: str = 'email public_profile'
linkedin_client_id: str | None = None
linkedin_client_secret: str | None = None
linkedin_scope: str = 'openid email profile'
bitbucket_client_id: str | None = None
bitbucket_client_secret: str | None = None
bitbucket_scope: str = 'account email'
get_configured_providers()[source]

Get a dictionary of configured providers with their credentials.

Return type:

dict[str, dict[str, str]]

Returns:

A dictionary mapping provider names to their configuration dictionaries. Each configuration includes client_id, client_secret, and scope.

Example:

config = OAuthConfig(
    redirect_base_url="https://example.com",
    github_client_id="id",
    github_client_secret="secret",
)
providers = config.get_configured_providers()
# {"github": {"client_id": "id", "client_secret": "secret", "scope": "user:email"}}
__init__(redirect_base_url, route_prefix='/auth', success_redirect='/dashboard', failure_redirect='/login?error=oauth', state_ttl=600, enabled_providers=None, github_client_id=None, github_client_secret=None, github_scope='user:email', google_client_id=None, google_client_secret=None, google_scope='openid email profile', discord_client_id=None, discord_client_secret=None, discord_scope='identify email', microsoft_client_id=None, microsoft_client_secret=None, microsoft_tenant_id='common', microsoft_scope='openid email profile', apple_client_id=None, apple_team_id=None, apple_key_id=None, apple_private_key=None, apple_scope='name email', gitlab_client_id=None, gitlab_client_secret=None, gitlab_url='https://gitlab.com', gitlab_scope='read_user', twitter_client_id=None, twitter_client_secret=None, twitter_scope='users.read tweet.read', facebook_client_id=None, facebook_client_secret=None, facebook_scope='email public_profile', linkedin_client_id=None, linkedin_client_secret=None, linkedin_scope='openid email profile', bitbucket_client_id=None, bitbucket_client_secret=None, bitbucket_scope='account email')
Parameters:
  • redirect_base_url (str)

  • route_prefix (str)

  • success_redirect (str)

  • failure_redirect (str)

  • state_ttl (int)

  • enabled_providers (Sequence[str] | None)

  • github_client_id (str | None)

  • github_client_secret (str | None)

  • github_scope (str)

  • google_client_id (str | None)

  • google_client_secret (str | None)

  • google_scope (str)

  • discord_client_id (str | None)

  • discord_client_secret (str | None)

  • discord_scope (str)

  • microsoft_client_id (str | None)

  • microsoft_client_secret (str | None)

  • microsoft_tenant_id (str)

  • microsoft_scope (str)

  • apple_client_id (str | None)

  • apple_team_id (str | None)

  • apple_key_id (str | None)

  • apple_private_key (str | None)

  • apple_scope (str)

  • gitlab_client_id (str | None)

  • gitlab_client_secret (str | None)

  • gitlab_url (str)

  • gitlab_scope (str)

  • twitter_client_id (str | None)

  • twitter_client_secret (str | None)

  • twitter_scope (str)

  • facebook_client_id (str | None)

  • facebook_client_secret (str | None)

  • facebook_scope (str)

  • linkedin_client_id (str | None)

  • linkedin_client_secret (str | None)

  • linkedin_scope (str)

  • bitbucket_client_id (str | None)

  • bitbucket_client_secret (str | None)

  • bitbucket_scope (str)

Testing Utilities

MockOAuthProvider

class litestar_oauth.testing.mocks.MockOAuthProvider[source]

Bases: object

Configurable mock OAuth provider for testing.

This mock implements the OAuthProvider protocol and can be configured to return specific responses for testing different OAuth flow scenarios.

Parameters:
  • provider_name (str) – Provider identifier (default: “mock”)

  • authorize_url (str) – Authorization endpoint URL

  • token_url (str) – Token exchange endpoint URL

  • user_info_url (str) – User info endpoint URL

  • scope (str) – OAuth scopes to request

  • configured (bool) – Whether provider has valid configuration

  • access_token (str) – Mock access token to return

  • refresh_token – Mock refresh token to return

  • user_info (Any) – Mock user info to return

  • raise_on_exchange (bool) – If True, raise exception during code exchange

  • raise_on_refresh (bool) – If True, raise exception during token refresh

  • raise_on_user_info (bool) – If True, raise exception when fetching user info

Example

>>> from litestar_oauth.types import OAuthUserInfo
>>> provider = MockOAuthProvider(
...     provider_name="github",
...     access_token="gho_mock_token",
...     user_info=OAuthUserInfo(
...         provider="github",
...         oauth_id="12345",
...         email="test@example.com",
...     ),
... )
>>> url = provider.get_authorization_url("http://localhost/callback", "state123")
>>> assert "state=state123" in url
Parameters:
provider_name: str = 'mock'
authorize_url: str = 'https://oauth.mock/authorize'
token_url: str = 'https://oauth.mock/token'
user_info_url: str = 'https://oauth.mock/userinfo'
scope: str = 'user:email'
configured: bool = True
access_token: str = 'mock_access_token'
mock_refresh_token: str | None = 'mock_refresh_token'
user_info: Any = None
raise_on_exchange: bool = False
raise_on_refresh: bool = False
raise_on_user_info: bool = False
is_configured()[source]

Check if provider is configured with required credentials.

Return type:

bool

get_authorization_url(redirect_uri, state, *, scope=None, extra_params=None)[source]

Generate OAuth authorization URL.

Parameters:
  • redirect_uri (str) – Callback URL after authorization

  • state (str) – CSRF protection token

  • scope (str | None) – Optional custom scopes (defaults to provider scope)

  • extra_params (dict[str, str] | None) – Additional query parameters

Return type:

str

Returns:

Full authorization URL with query parameters

async exchange_code(code, redirect_uri)[source]

Exchange authorization code for access token.

Parameters:
  • code (str) – Authorization code from OAuth callback

  • redirect_uri (str) – Callback URL (must match initial request)

Return type:

Any

Returns:

OAuthToken with access token and optional refresh token

Raises:

Exception – If raise_on_exchange is True

async refresh_token(refresh_token)[source]

Refresh an expired access token.

Parameters:

refresh_token (str) – Refresh token from original token exchange

Return type:

Any

Returns:

OAuthToken with new access token

Raises:

Exception – If raise_on_refresh is True

async get_user_info(access_token)[source]

Fetch user profile information.

Parameters:

access_token (str) – Valid OAuth access token

Return type:

Any

Returns:

OAuthUserInfo with user profile data

Raises:

Exception – If raise_on_user_info is True

async revoke_token(token, *, token_type_hint='access_token')[source]

Revoke an access or refresh token.

Parameters:
  • token (str) – Token to revoke

  • token_type_hint (str) – Type of token (access_token or refresh_token)

Return type:

None

__init__(provider_name='mock', authorize_url='https://oauth.mock/authorize', token_url='https://oauth.mock/token', user_info_url='https://oauth.mock/userinfo', scope='user:email', configured=True, access_token='mock_access_token', mock_refresh_token='mock_refresh_token', user_info=None, raise_on_exchange=False, raise_on_refresh=False, raise_on_user_info=False, _http_client=None)
Parameters: