API Reference¶
Complete API documentation for litestar-oauth.
Core Types¶
OAuthUserInfo¶
- class litestar_oauth.types.OAuthUserInfo[source]
Bases:
objectUser information retrieved from an OAuth provider.
- provider
Name of the OAuth provider (e.g., ‘google’, ‘github’).
- oauth_id
Unique identifier from the OAuth provider.
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_verified:
bool
- 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>)
OAuthToken¶
- class litestar_oauth.types.OAuthToken[source]
Bases:
objectOAuth2 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
- 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>)
OAuthState¶
- class litestar_oauth.types.OAuthState[source]
Bases:
objectState 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
Service¶
OAuthService¶
- class litestar_oauth.service.OAuthService[source]
Bases:
objectCentral 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.
- __init__(providers=None, state_manager=None)[source]
Initialize the OAuth service.
- 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:
- 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.
- 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:
- 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:
objectIn-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:
- 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:
- 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:
- Returns:
Number of expired states removed.
Base Classes¶
BaseOAuthProvider¶
- class litestar_oauth.base.BaseOAuthProvider[source]
Bases:
ABCAbstract 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.
- __init__(client_id, client_secret, scope=None)[source]
Initialize the OAuth provider with credentials.
- 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.
- is_configured()[source]
Check if the provider has required configuration.
- Return type:
- Returns:
True if client_id and client_secret are set.
- async get_authorization_url(redirect_uri, state, **kwargs)[source]
Generate authorization URL.
- async exchange_code(code, redirect_uri, **kwargs)[source]
Exchange authorization code for access token.
- async refresh_token(refresh_token, **kwargs)[source]
Refresh an access token.
- abstractmethod async get_user_info(access_token, **kwargs)[source]
Fetch user information.
- 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.
OAuthProvider¶
- class litestar_oauth.base.OAuthProvider[source]
Bases:
ProtocolProtocol 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.
- is_configured()[source]
Check if the provider has all required configuration.
- Return type:
- 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.
- async exchange_code(code, redirect_uri, **kwargs)[source]
Exchange an authorization code for an access token.
- 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.
- async get_user_info(access_token, **kwargs)[source]
Retrieve user information using an access token.
- async revoke_token(token, token_type_hint=None, **kwargs)[source]
Revoke an access or refresh token.
- __init__(*args, **kwargs)
Providers¶
GitHubOAuthProvider¶
- class litestar_oauth.providers.github.GitHubOAuthProvider[source]
Bases:
BaseOAuthProviderGitHub 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:
- 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:
- Return type:
OAuthUserInfo- Returns:
Normalized user information.
- Raises:
ImportError – If httpx is not installed.
Exception – If user info fetch fails.
GoogleOAuthProvider¶
- class litestar_oauth.providers.google.GoogleOAuthProvider[source]
Bases:
BaseOAuthProviderGoogle 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:
- 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:
- Return type:
OAuthUserInfo- Returns:
Normalized user information.
- Raises:
ImportError – If httpx is not installed.
Exception – If user info fetch fails.
DiscordOAuthProvider¶
- class litestar_oauth.providers.discord.DiscordOAuthProvider[source]
Bases:
BaseOAuthProviderDiscord 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:
- 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:
- Return type:
OAuthUserInfo- Returns:
Normalized user information.
- Raises:
ImportError – If httpx is not installed.
Exception – If user info fetch fails.
GenericOAuthProvider¶
- class litestar_oauth.providers.generic.GenericOAuthProvider[source]
Bases:
BaseOAuthProviderGeneric 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.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:
ImportError – If httpx is not installed.
ValueError – If discovery_url is not set.
Exception – If discovery fails.
- Return type:
- 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:
- Return type:
OAuthUserInfo- Returns:
Normalized user information.
- Raises:
ImportError – If httpx is not installed.
ValueError – If user_info_url is not configured.
Exception – If user info fetch fails.
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:
StateValidationErrorRaised 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:
StateValidationErrorRaised 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:
ExceptionBase 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:
OAuthErrorRaised 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:
OAuthErrorBase 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:
OAuthErrorRaised 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:
OAuthErrorRaised 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:
OAuthErrorRaised 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:
objectConfiguration 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)github_scope (
str)google_scope (
str)discord_scope (
str)microsoft_tenant_id (
str)microsoft_scope (
str)apple_scope (
str)gitlab_url (
str)gitlab_scope (
str)twitter_scope (
str)facebook_scope (
str)linkedin_scope (
str)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
-
github_scope:
str= 'user:email'
-
google_scope:
str= 'openid email profile'
-
discord_scope:
str= 'identify email'
-
microsoft_tenant_id:
str= 'common'
-
microsoft_scope:
str= 'openid email profile'
-
apple_scope:
str= 'name email'
-
gitlab_url:
str= 'https://gitlab.com'
-
gitlab_scope:
str= 'read_user'
-
twitter_scope:
str= 'users.read tweet.read'
-
facebook_scope:
str= 'email public_profile'
-
linkedin_scope:
str= 'openid email profile'
-
bitbucket_scope:
str= 'account email'
- get_configured_providers()[source]
Get a dictionary of configured providers with their credentials.
- Return type:
- 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)github_scope (
str)google_scope (
str)discord_scope (
str)microsoft_tenant_id (
str)microsoft_scope (
str)apple_scope (
str)gitlab_url (
str)gitlab_scope (
str)twitter_scope (
str)facebook_scope (
str)linkedin_scope (
str)bitbucket_scope (
str)
Testing Utilities¶
MockOAuthProvider¶
- class litestar_oauth.testing.mocks.MockOAuthProvider[source]
Bases:
objectConfigurable 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 URLtoken_url (
str) – Token exchange endpoint URLuser_info_url (
str) – User info endpoint URLscope (
str) – OAuth scopes to requestconfigured (
bool) – Whether provider has valid configurationaccess_token (
str) – Mock access token to returnrefresh_token – Mock refresh token to return
user_info (
Any) – Mock user info to returnraise_on_exchange (
bool) – If True, raise exception during code exchangeraise_on_refresh (
bool) – If True, raise exception during token refreshraise_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
-
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'
-
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:
- get_authorization_url(redirect_uri, state, *, scope=None, extra_params=None)[source]
Generate OAuth authorization URL.
- Parameters:
- Return type:
- Returns:
Full authorization URL with query parameters
- async exchange_code(code, redirect_uri)[source]
Exchange authorization code for access token.
- async refresh_token(refresh_token)[source]
Refresh an expired access token.
- async get_user_info(access_token)[source]
Fetch user profile information.
- async revoke_token(token, *, token_type_hint='access_token')[source]
Revoke an access or refresh token.
- __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)