CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-social-auth-core

Python social authentication framework with 195+ backend providers for OAuth, OpenID Connect, and SAML integration.

Pending
Overview
Eval results
Files

authentication-backends.mddocs/

Authentication Backends

Social Auth Core provides 195+ authentication backend implementations supporting OAuth 1.0/2.0, OpenID Connect, SAML, and custom authentication protocols. Each backend handles provider-specific authentication flows, token management, user data extraction, and API integration.

Capabilities

Base Authentication Backend

The foundation class that all authentication backends inherit from, providing the core authentication interface and common functionality.

class BaseAuth:
    """
    Base authentication backend class.
    
    All authentication backends inherit from this class and implement
    provider-specific authentication logic while maintaining a consistent interface.
    """
    
    # Class attributes
    name: str = ""  # Provider name stored in database
    supports_inactive_user: bool = False  # Django auth compatibility
    ID_KEY: str = ""  # Key for extracting user ID from provider response
    EXTRA_DATA: list | None = None  # Additional data fields to store
    GET_ALL_EXTRA_DATA: bool = False  # Store all provider response data
    REQUIRES_EMAIL_VALIDATION: bool = False  # Email validation requirement
    SEND_USER_AGENT: bool = False  # Send User-Agent header
    
    def __init__(self, strategy, redirect_uri=None):
        """
        Initialize backend with strategy and redirect URI.
        
        Parameters:
        - strategy: Strategy instance for framework integration
        - redirect_uri: Callback URL for OAuth flows (optional)
        """
        
    def setting(self, name, default=None):
        """
        Get setting value from strategy with backend-specific prefixing.
        
        Parameters:
        - name: Setting name
        - default: Default value if setting not found
        
        Returns:
        Setting value or default
        """
        
    def start(self):
        """
        Start authentication flow.
        
        Returns:
        Redirect response to provider or HTML content
        """
        
    def complete(self, *args, **kwargs):
        """
        Complete authentication flow.
        
        Returns:
        Authenticated user instance
        """
        
    def auth_url(self) -> str:
        """
        Generate authentication URL for provider.
        
        Returns:
        URL string for redirecting user to provider
        
        Raises:
        NotImplementedError: Must be implemented by subclasses
        """
        
    def auth_html(self) -> str:
        """
        Generate authentication HTML for non-redirect flows.
        
        Returns:
        HTML string for authentication
        """
        
    def auth_complete(self, *args, **kwargs):
        """
        Handle provider callback and complete authentication.
        
        Returns:
        User data or authentication result
        
        Raises:
        NotImplementedError: Must be implemented by subclasses
        """
        
    def authenticate(self, *args, **kwargs):
        """
        Authenticate user using social credentials.
        
        This method validates the backend matches the request and runs
        the authentication pipeline to create or retrieve the user.
        
        Parameters:
        - backend: Backend instance (must match self.name)
        - strategy: Strategy instance
        - response: Provider response data
        - Additional args/kwargs passed to pipeline
        
        Returns:
        Authenticated user instance or None
        """
        
    def pipeline(self, pipeline, pipeline_index=0, *args, **kwargs):
        """
        Run authentication pipeline.
        
        Parameters:
        - pipeline: List of pipeline function names
        - pipeline_index: Starting index in pipeline
        - Additional args/kwargs for pipeline functions
        
        Returns:
        User instance with social_user and is_new attributes
        """
    
    def disconnect(self, *args, **kwargs):
        """
        Disconnect social account from user.
        
        Returns:
        Dictionary with disconnection results
        """
        
    def get_user_details(self, response):
        """
        Extract user details from provider response.
        
        Parameters:
        - response: Provider response data
        
        Returns:
        Dictionary with user details (username, email, full_name, etc.)
        
        Raises:
        NotImplementedError: Must be implemented by subclasses
        """
        
    def get_user_id(self, details, response):
        """
        Extract user ID from provider response.
        
        Parameters:
        - details: User details dictionary
        - response: Provider response data
        
        Returns:
        String user ID from provider
        """
        
    def get_user(self, user_id):
        """
        Get user instance by ID.
        
        Parameters:
        - user_id: User ID to lookup
        
        Returns:
        User instance or None
        """
        
    def request(self, url, method="GET", *, headers=None, data=None, auth=None, params=None):
        """
        Make HTTP request to provider API.
        
        Parameters:
        - url: Request URL
        - method: HTTP method ("GET", "POST", "DELETE")
        - headers: Request headers dictionary
        - data: Request body data
        - auth: Authentication credentials
        - params: Query parameters
        
        Returns:
        HTTP response object
        """
        
    def get_json(self, url, method="GET", *, headers=None, data=None, auth=None, params=None):
        """
        Make HTTP request and parse JSON response.
        
        Parameters:
        - url: Request URL
        - method: HTTP method
        - headers: Request headers
        - data: Request body
        - auth: Authentication credentials
        - params: Query parameters
        
        Returns:
        Parsed JSON response as dictionary
        """

OAuth Base Classes

Base classes that provide OAuth-specific functionality for OAuth 1.0 and 2.0 authentication flows.

class OAuthAuth(BaseAuth):
    """
    Base OAuth authentication backend for OAuth 1.0 and 2.0 flows.
    
    Provides common OAuth functionality including token management,
    state validation, scope handling, and authorization URL generation.
    """
    
    # OAuth-specific class attributes
    AUTHORIZATION_URL: str = ""  # Provider authorization endpoint
    ACCESS_TOKEN_URL: str = ""  # Provider token exchange endpoint
    ACCESS_TOKEN_METHOD: str = "POST"  # HTTP method for token requests
    REVOKE_TOKEN_URL: str = ""  # Token revocation endpoint
    REVOKE_TOKEN_METHOD: str = "POST"  # HTTP method for revocation
    SCOPE_PARAMETER_NAME: str = "scope"  # Parameter name for scope
    DEFAULT_SCOPE: list = []  # Default OAuth scopes
    SCOPE_SEPARATOR: str = " "  # Scope separator in requests
    REDIRECT_STATE: bool = True  # Use state parameter for security
    STATE_PARAMETER: str = "state"  # State parameter name
    
    def extra_data(self, user, uid, response, details=None, *args, **kwargs):
        """
        Return extra user data from provider response.
        
        Parameters:
        - user: User instance
        - uid: Provider user ID
        - response: Provider response data
        - details: User details dictionary
        
        Returns:
        Dictionary of extra data to store with social account
        """
        
    def state_token(self):
        """
        Generate state token for OAuth security.
        
        Returns:
        Random state token string
        """
        
    def get_or_create_state(self):
        """
        Get existing state from session or create new one.
        
        Returns:
        State token string or None
        """
        
    def get_session_state(self):
        """
        Get state from current session.
        
        Returns:
        State token from session
        """
        
    def get_request_state(self):
        """
        Get state from current request.
        
        Returns:
        State token from request parameters
        """

OAuth 2.0 Backends

Popular OAuth 2.0 provider implementations for major social platforms and services.

# Google OAuth 2.0
class GoogleOAuth2(BaseAuth):
    """Google OAuth 2.0 authentication backend."""
    name = "google-oauth2"
    
# Facebook OAuth 2.0  
class FacebookOAuth2(BaseAuth):
    """Facebook OAuth 2.0 authentication backend."""
    name = "facebook"
    
# GitHub OAuth 2.0
class GithubOAuth2(BaseAuth):
    """GitHub OAuth 2.0 authentication backend."""
    name = "github"
    
# Twitter OAuth 2.0 (new API)
class TwitterOAuth2(BaseAuth):
    """Twitter OAuth 2.0 authentication backend."""
    name = "twitter-oauth2"
    
# LinkedIn OAuth 2.0
class LinkedinOAuth2(BaseAuth):
    """LinkedIn OAuth 2.0 authentication backend."""
    name = "linkedin-oauth2"
    
# Microsoft Azure AD OAuth 2.0
class AzureADOAuth2(BaseAuth):
    """Azure AD OAuth 2.0 authentication backend."""  
    name = "azuread-oauth2"
    
# Apple OAuth 2.0
class AppleIdAuth(BaseAuth):
    """Apple Sign In authentication backend."""
    name = "apple-id"
    
# Discord OAuth 2.0
class DiscordOAuth2(BaseAuth):
    """Discord OAuth 2.0 authentication backend."""
    name = "discord"
    
# Slack OAuth 2.0
class SlackOAuth2(BaseAuth):
    """Slack OAuth 2.0 authentication backend."""
    name = "slack-oauth2"

OAuth 1.0 Backends

OAuth 1.0a implementations for providers that still use the older OAuth standard.

# Twitter OAuth 1.0a (legacy API)
class TwitterOAuth(BaseAuth):
    """Twitter OAuth 1.0a authentication backend."""
    name = "twitter"
    
# Flickr OAuth 1.0a
class FlickrOAuth(BaseAuth):
    """Flickr OAuth 1.0a authentication backend."""  
    name = "flickr"

OpenID Connect Backends

OpenID Connect implementations for identity providers supporting the OIDC standard.

class OpenIdConnectAuth(OAuthAuth):
    """
    Generic OpenID Connect authentication backend.
    
    Provides standards-compliant OIDC authentication with JWT token validation,
    userinfo endpoint integration, and configurable OIDC discovery.
    """
    name = "oidc"
    
    # OIDC-specific constants
    OIDC_ENDPOINT: str = ""  # Base OIDC endpoint URL
    ID_TOKEN_MAX_AGE: int = 600  # Maximum ID token age in seconds
    DEFAULT_SCOPE: list = ["openid", "profile", "email"]
    EXTRA_DATA: list = ["id_token", "refresh_token", "token_type"]
    REDIRECT_STATE: bool = True
    REVOKE_TOKEN_METHOD: str = "POST"
    ID_KEY: str = "sub"  # Subject claim from ID token
    USERNAME_KEY: str = "preferred_username"
    JWT_ALGORITHMS: list = ["RS256"]  # Supported JWT algorithms
    JWT_DECODE_OPTIONS: dict = {"verify_aud": True}
    JWT_LEEWAY: int = 0  # Clock skew allowance in seconds
    
    def __init__(self, *args, **kwargs):
        """
        Initialize OIDC backend with configuration.
        
        Loads OIDC configuration from settings including endpoints,
        client credentials, and JWT validation parameters.
        """
        
    def get_setting_config(self, setting_name, oidc_name, default):
        """
        Get OIDC-specific setting with fallback hierarchy.
        
        Parameters:
        - setting_name: Base setting name
        - oidc_name: OIDC provider name for namespaced settings
        - default: Default value if setting not found
        
        Returns:
        Setting value with OIDC-specific overrides applied
        """
        
    def authorization_url(self):
        """
        Generate OIDC authorization URL.
        
        Returns:
        Complete authorization URL with OIDC parameters
        """

class Auth0(OpenIdConnectAuth):
    """Auth0 OpenID Connect authentication backend."""
    name = "auth0"

SAML Backends

SAML 2.0 implementation for enterprise single sign-on integration.

class SAMLAuth(BaseAuth):
    """SAML 2.0 authentication backend."""
    name = "saml"
    
    def __init__(self, strategy, redirect_uri=None, idp=None):
        """
        Initialize SAML backend.
        
        Parameters:
        - strategy: Strategy instance
        - redirect_uri: Callback URL
        - idp: Identity Provider configuration
        """

Backend Utilities

Helper functions for backend discovery, loading, and management.

def get_backend(backends, name):
    """
    Get backend by name from backends list.
    
    Parameters:
    - backends: List of available backend classes
    - name: Backend name to find
    
    Returns:
    Backend class or None if not found
    """
    
def load_backends(backend_names, strategy):
    """
    Load backend instances from configuration.
    
    Parameters:
    - backend_names: List of backend names to load
    - strategy: Strategy instance
    
    Returns:
    Dictionary mapping backend names to instances
    """

Usage Examples

Basic Backend Usage

from social_core.backends.google import GoogleOAuth2

# Initialize backend
backend = GoogleOAuth2(
    strategy=my_strategy,
    redirect_uri='https://myapp.com/auth/complete/google/'
)

# Start authentication flow
auth_response = backend.start()  # Returns redirect to Google

# In callback handler, complete authentication
user = backend.complete(user=current_user)

Custom Backend Implementation

from social_core.backends.oauth import BaseOAuth2

class CustomOAuth2(BaseOAuth2):
    """Custom OAuth 2.0 provider backend."""
    name = 'custom-provider'
    AUTHORIZATION_URL = 'https://provider.com/oauth/authorize'
    ACCESS_TOKEN_URL = 'https://provider.com/oauth/token'
    ACCESS_TOKEN_METHOD = 'POST'
    ID_KEY = 'id'
    
    def get_user_details(self, response):
        """Extract user details from provider response."""
        return {
            'username': response.get('login'),
            'email': response.get('email'),
            'first_name': response.get('name', '').split(' ')[0],
        }
    
    def user_data(self, access_token, *args, **kwargs):
        """Fetch user data from provider API."""
        return self.get_json(
            'https://provider.com/api/user',
            headers={'Authorization': f'Bearer {access_token}'}
        )

Backend Configuration

Backends are configured through settings with provider-specific keys:

# Google OAuth 2.0 configuration
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'your-client-id'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'your-client-secret'
SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ['openid', 'email', 'profile']

# GitHub OAuth 2.0 configuration  
SOCIAL_AUTH_GITHUB_KEY = 'your-github-client-id'
SOCIAL_AUTH_GITHUB_SECRET = 'your-github-client-secret'
SOCIAL_AUTH_GITHUB_SCOPE = ['user:email']

# SAML configuration
SOCIAL_AUTH_SAML_SP_ENTITY_ID = 'https://myapp.com'
SOCIAL_AUTH_SAML_SP_PUBLIC_CERT = '/path/to/cert.pem'
SOCIAL_AUTH_SAML_SP_PRIVATE_KEY = '/path/to/key.pem'

The extensive backend collection covers major social platforms, enterprise identity providers, and specialized services, enabling integration with virtually any OAuth, OpenID Connect, or SAML-compatible authentication system.

Install with Tessl CLI

npx tessl i tessl/pypi-social-auth-core

docs

authentication-actions.md

authentication-backends.md

exception-handling.md

index.md

pipeline-system.md

storage-models.md

strategy-interface.md

utilities-helpers.md

tile.json