Python social authentication framework with 195+ backend providers for OAuth, OpenID Connect, and SAML integration.
—
Collection of utility functions and helper classes that support the social authentication process. These utilities handle URL manipulation, session management, pipeline data processing, user validation, security operations, and other common tasks used throughout the authentication workflow.
Functions for dynamic module loading and member access by string paths.
def import_module(name: str):
"""
Import module by string name.
Dynamically imports a Python module using its string name,
useful for loading backends and pipeline functions from configuration.
Parameters:
- name: Module name string (e.g., 'social_core.backends.google')
Returns:
Imported module object
"""
def module_member(name: str):
"""
Get module member by dotted path.
Imports a module and returns a specific member (class, function, variable)
using a dotted path notation.
Parameters:
- name: Dotted path to member (e.g., 'social_core.backends.google.GoogleOAuth2')
Returns:
Module member object (class, function, etc.)
Example:
backend_class = module_member('social_core.backends.google.GoogleOAuth2')
"""Functions for handling HTTP requests, User-Agent strings, and network-related operations.
def user_agent() -> str:
"""
Build User-Agent string for HTTP requests.
Creates a standardized User-Agent header string that identifies
requests as coming from social-auth-core with version information.
Returns:
User-Agent string in format 'social-auth-{version}'
Example:
'social-auth-4.7.0'
"""Functions for URL parsing, parameter manipulation, and validation.
def url_add_parameters(url: str, params: dict | None, _unquote_query: bool = False) -> str:
"""
Add parameters to URL query string.
Appends parameters to a URL's query string, handling existing parameters
and proper URL encoding. Parameters will be repeated if already present.
Parameters:
- url: Base URL string
- params: Dictionary of parameters to add (optional)
- _unquote_query: Whether to unquote existing query parameters (default: False)
Returns:
URL string with added parameters
Example:
url_add_parameters('https://example.com', {'foo': 'bar'})
# Returns: 'https://example.com?foo=bar'
"""
def parse_qs(value: str, keep_blank_values: bool = False, strict_parsing: bool = False):
"""
Parse query string into dictionary.
Enhanced query string parsing with additional options for handling
blank values and strict parsing mode.
Parameters:
- value: Query string to parse
- keep_blank_values: Whether to keep parameters with blank values
- strict_parsing: Whether to raise errors on parsing failures
Returns:
Dictionary with parameter names as keys and lists of values
"""
def get_querystring(url: str) -> dict:
"""
Extract query parameters from URL.
Parameters:
- url: URL string with query parameters
Returns:
Dictionary of query parameters
"""
def drop_lists(value: dict) -> dict:
"""
Convert list values to single values in dictionary.
Takes a dictionary that may have list values (like from query parsing)
and converts single-item lists to scalar values.
Parameters:
- value: Dictionary with potential list values
Returns:
Dictionary with scalar values where possible
"""
def is_url(value: str) -> bool:
"""
Check if string is a valid URL.
Parameters:
- value: String to validate
Returns:
Boolean indicating if string is a valid URL
"""
def append_slash(url: str) -> str:
"""
Add trailing slash to URL if missing.
Parameters:
- url: URL string
Returns:
URL string with trailing slash
"""
def build_absolute_uri(host_url: str, path: str | None = None) -> str:
"""
Build absolute URI from host and path.
Parameters:
- host_url: Base host URL
- path: Optional path to append
Returns:
Complete absolute URI
"""Functions for security operations, redirect validation, and input sanitization.
def sanitize_redirect(allowed_hosts: list, redirect_uri: str) -> str | None:
"""
Sanitize redirect URI for security.
Validates a redirect URI against a list of allowed hosts to prevent
open redirect vulnerabilities and malicious redirections.
Parameters:
- allowed_hosts: List of allowed host names/domains
- redirect_uri: URI to validate and sanitize
Returns:
Sanitized URI string if valid, None if invalid/unsafe
Example:
sanitize_redirect(['myapp.com'], 'https://myapp.com/dashboard')
# Returns: 'https://myapp.com/dashboard'
sanitize_redirect(['myapp.com'], 'https://evil.com/steal')
# Returns: None
"""
def setting_url(backend, name: str, default: str | None = None) -> str:
"""
Get URL setting with proper validation.
Retrieves a URL-type setting from backend configuration with
validation and default value handling.
Parameters:
- backend: Authentication backend instance
- name: Setting name
- default: Default URL if setting not found
Returns:
Validated URL string
"""
def constant_time_compare(val1: str, val2: str) -> bool:
"""
Compare two strings in constant time to prevent timing attacks.
Parameters:
- val1: First string to compare
- val2: Second string to compare
Returns:
Boolean indicating if strings are equal
"""
def slugify(value: str) -> str:
"""
Convert string to URL-safe slug format.
Parameters:
- value: String to slugify
Returns:
URL-safe slug string
"""
def first(func, items):
"""
Return first item from iterable that matches function.
Parameters:
- func: Function to test items with
- items: Iterable of items to test
Returns:
First matching item or None
"""
def handle_http_errors(func):
"""
Decorator to handle HTTP errors in API requests.
Parameters:
- func: Function to wrap
Returns:
Decorated function that handles HTTP errors
"""Functions for checking user authentication and activation status.
def user_is_authenticated(user) -> bool:
"""
Check if user is authenticated.
Framework-agnostic check for user authentication status,
handling different user model implementations.
Parameters:
- user: User instance to check
Returns:
Boolean indicating if user is authenticated
Example:
if user_is_authenticated(request.user):
# User is logged in
pass
"""
def user_is_active(user) -> bool:
"""
Check if user account is active.
Framework-agnostic check for user account activation status,
handling different user model implementations.
Parameters:
- user: User instance to check
Returns:
Boolean indicating if user account is active
Example:
if user_is_active(user):
# User account is enabled
pass
"""Functions for managing partial pipeline data and authentication state.
def partial_pipeline_data(backend, user, *args, **kwargs):
"""
Get partial pipeline data for current authentication.
Retrieves stored partial pipeline data if the current authentication
flow was interrupted and needs to be resumed.
Parameters:
- backend: Authentication backend instance
- user: Current user instance
- Additional arguments from authentication flow
Returns:
Partial pipeline data object or None if no partial data exists
Example:
partial = partial_pipeline_data(backend, user)
if partial:
# Resume interrupted authentication
user = backend.continue_pipeline(partial)
"""Functions and constants for handling social auth configuration.
# Configuration constants
SETTING_PREFIX: str = "SOCIAL_AUTH"
"""
Prefix used for all social auth configuration settings.
All social auth settings follow the pattern:
SOCIAL_AUTH_<BACKEND>_<SETTING> or SOCIAL_AUTH_<SETTING>
Example:
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY
SOCIAL_AUTH_LOGIN_REDIRECT_URL
"""
PARTIAL_TOKEN_SESSION_NAME: str = "partial_pipeline_token"
"""
Session key name for storing partial pipeline tokens.
Used to store tokens that identify interrupted authentication
flows that can be resumed later.
"""
def setting_name(backend, name: str) -> str:
"""
Generate setting name with proper prefixing.
Creates the full setting name using the social auth prefix
and backend-specific naming conventions.
Parameters:
- backend: Authentication backend instance
- name: Base setting name
Returns:
Full setting name string
Example:
setting_name(google_backend, 'KEY')
# Returns: 'SOCIAL_AUTH_GOOGLE_OAUTH2_KEY'
"""Logging configuration and utilities for debugging social authentication.
social_logger: logging.Logger
"""
Logger instance for social authentication operations.
Pre-configured logger with name 'social' for consistent logging
across social auth components.
Example:
from social_core.utils import social_logger
social_logger.info('Authentication started for user %s', username)
"""Functions for string manipulation and data processing.
def slugify_username(username: str) -> str:
"""
Convert username to URL-safe slug format.
Processes usernames to remove special characters and create
URL-safe versions suitable for use in web applications.
Parameters:
- username: Original username string
Returns:
Slugified username string
"""
def handle_http_errors(func):
"""
Decorator for handling HTTP errors in backend methods.
Catches common HTTP exceptions and converts them to
appropriate social auth exceptions with better error messages.
Parameters:
- func: Function to wrap with error handling
Returns:
Wrapped function with error handling
"""Functions for cryptographic operations and security.
def build_absolute_uri(host: str, path: str | None = None) -> str:
"""
Build absolute URI from host and path components.
Constructs a complete URI from separate host and path components,
handling proper URL formatting and encoding.
Parameters:
- host: Host name or base URL
- path: Path component (optional)
Returns:
Complete absolute URI string
"""
def constant_time_compare(val1: str, val2: str) -> bool:
"""
Compare two strings in constant time.
Performs string comparison that takes the same amount of time
regardless of where the strings differ, preventing timing attacks.
Parameters:
- val1: First string to compare
- val2: Second string to compare
Returns:
Boolean indicating if strings are equal
"""from social_core.utils import module_member
# Load backend class dynamically
backend_path = 'social_core.backends.google.GoogleOAuth2'
BackendClass = module_member(backend_path)
# Create backend instance
backend = BackendClass(strategy, redirect_uri='/auth/complete/')from social_core.utils import url_add_parameters
base_url = 'https://accounts.google.com/oauth/authorize'
params = {
'client_id': '12345',
'redirect_uri': 'https://myapp.com/auth/complete/',
'scope': 'openid email profile',
'response_type': 'code'
}
auth_url = url_add_parameters(base_url, params)
# Result: https://accounts.google.com/oauth/authorize?client_id=12345&redirect_uri=...from social_core.utils import sanitize_redirect
allowed_hosts = ['myapp.com', 'subdomain.myapp.com']
user_redirect = request.GET.get('next', '/')
safe_redirect = sanitize_redirect(allowed_hosts, user_redirect)
if safe_redirect:
return redirect(safe_redirect)
else:
# Invalid redirect, use default
return redirect('/')from social_core.utils import user_is_authenticated, user_is_active
def require_auth(user):
if not user_is_authenticated(user):
raise AuthException('User not authenticated')
if not user_is_active(user):
raise AuthException('User account is inactive')
return userThe utilities and helpers provide essential functionality for secure, robust social authentication while maintaining framework independence and security best practices.
Install with Tessl CLI
npx tessl i tessl/pypi-social-auth-core