API Reference

This reference covers the main extension points provided by social-auth-core. The generated pages include links to the corresponding source code.

Authentication backends

class social_core.backends.base.BaseAuth(strategy: BaseStrategy | None = None, redirect_uri: str | None = None)[source]

Bases: object

A authentication backend that authenticates the user based on the provider response.

Set ASSOCIATION_ONLY to connect provider access to an authenticated local user without updating their profile. Browser flows must start through do_auth(user=...) and validate callbacks with validate_association_state() before processing provider credentials. Authentication and disconnect partials remain bound to that local user.

ASSOCIATION_ONLY = False
EXTRA_DATA: list[str | tuple[str, str] | tuple[str, str, bool]] | None = None
GET_ALL_EXTRA_DATA = False
ID_KEY: str = ''
LEGACY_ID_KEYS: tuple[str, ...] = ()
MUTABLE_ID_KEYS: tuple[str, ...] = ()
REQUIRES_EMAIL_VALIDATION = False
REQUIRES_USER_ID: bool = False
SEND_USER_AGENT = True
association_user_id_key(pipeline_type: str = 'authentication') → str[source]

Name of the initiator binding saved in pipeline arguments.

auth_allowed(response, details)[source]

Return True if the user should be allowed to authenticate, by default check if email is whitelisted (if there’s a whitelist)

auth_complete(*args, **kwargs) → HttpResponseProtocol | UserProtocol | None[source]

Completes login process, must return user instance

auth_extra_arguments() → dict[str, str][source]

Return extra arguments needed on auth process.

Configured AUTH_EXTRA_ARGUMENTS are not overridden by request data by default. Set AUTH_EXTRA_ARGUMENTS_OVERRIDE_ALLOWLIST to an iterable of configured extra-argument keys that may be replaced by matching request data values.

auth_html() → str[source]

Must return login HTML content returned by provider

auth_url() → str[source]

Must return redirect URL to auth provider

authenticate(*args, **kwargs) → UserProtocol | HttpResponseProtocol | None[source]

Authenticate user using social credentials

Authentication is made if this is the correct backend, backend verification is made by kwargs inspection for current backend name presence.

complete(*args, **kwargs) → HttpResponseProtocol | UserProtocol | None[source]
continue_disconnect_pipeline(partial: PartialMixin) → dict | HttpResponseProtocol[source]

Continue a halted disconnect with its effective request data.

continue_pipeline(partial: PartialMixin) → UserProtocol | HttpResponseProtocol | None[source]

Continue previous halted pipeline

disconnect(*args, **kwargs) → dict[source]
extra_data(user: UserProtocol | None, uid: str, response: dict[str, Any], details: dict[str, Any], pipeline_kwargs: dict[str, Any]) → dict[str, Any][source]

Return default extra data to store in extra_data field

get_association_state() → str[source]

Return the token from a prepared, user-bound authorization context.

get_group_mappings()[source]

Enumerate independently managed membership sources.

get_group_setting(name: str, response, default=None)[source]

Resolve group configuration for this provider (or a SAML IdP).

get_group_source(response) → str[source]

Identify the provider’s active membership source.

get_json(url: str, method: Literal['GET', 'POST', 'DELETE'] = 'GET', headers: Mapping[str, str | bytes] | None = None, data: dict | None = None, json: dict | None = None, auth: tuple[str, str] | AuthBase | None = None, params: dict | None = None, timeout: float | None = None, stage: ErrorStage = 'user_info') → dict[Any, Any][source]
get_key_and_secret() → tuple[str, str][source]

Return tuple with Consumer Key and Consumer Secret for current service provider. Must return (key, secret), order must be respected.

get_key_and_secret_basic_auth() → bytes[source]

Generate HTTP Basic Authentication header value from KEY and SECRET.

Returns:

Basic authentication value in the format b”Basic <base64-encoded-credentials>”

get_legacy_user_ids(details, response) → list[str][source]

Return current values of identifiers used by older releases.

get_querystring(url, *args, **kwargs) → dict[str, str][source]
get_refresh_token(extra_data: dict[str, Any]) → str | None[source]

Select a stored renewal credential, or None when renewal is unavailable.

Backends that exchange an access token should override this method.

get_refresh_token_kwargs(extra_data: dict[str, Any]) → dict[str, Any][source]

Return default refresh arguments from stored account credentials.

get_user(user_id)[source]

Return user with given ID from the User model used by this backend. This is called by django.contrib.auth.middleware.

get_user_details(response) → dict[str, Any][source]

Return provider-supplied user details in a known internal structure.

Leave name conversion to the social_names pipeline step.

The returned dictionary can contain:

username

Username, if any.

email

User email, if any.

fullname

User full name, if any.

first_name

User first name, if any.

last_name

User last name, if any.

get_user_groups(response) → list[str] | None[source]

Return normalized external memberships, or None when disabled.

get_user_id(details, response)[source]

Return a unique ID for the current user, by default from server response or details.

get_user_id_for_key(details, response, id_key: str)[source]

Return a user identifier selected by an explicit response key.

get_user_id_from_sources(*sources: Mapping[str, Any] | None, id_key: str | None = None)[source]

Return the selected user ID from mappings or fail clearly.

Sources are searched in order for the configured or explicitly passed ID key. Missing, None, and empty-string values are rejected.

get_user_names(fullname='', first_name='', last_name='')[source]
icon: str | None = None
id_key() → str[source]

Return the ID_KEY to use for this backend, checking settings first.

log_debug(message, *args) → None[source]
log_warning(message, *args) → None[source]
name = ''
pipeline(pipeline, pipeline_index: int = 0, *args, **kwargs) → UserProtocol | HttpResponseProtocol | None[source]
property pipeline_type: str

Type of the currently executing pipeline, saved with its partials.

prepare_auth(user: UserProtocol | None = None) → None[source]

Bind association-only authorization to an authenticated local user.

process_error(data, *, stage: Literal['begin', 'callback', 'token_exchange', 'token_validation', 'user_info', 'pipeline', 'refresh', 'disconnect', 'unknown'] = 'callback') → None[source]

Hook to process provider response errors.

Default implementation is a no-op. Backends that can detect provider-specific error payloads should override this method and raise an appropriate exception when needed.

request(url: str, *, method: Literal['GET', 'POST', 'DELETE'] = 'GET', headers: Mapping[str, str | bytes] | None = None, data: dict | None = None, json: dict | None = None, auth: tuple[str, str] | AuthBase | None = None, params: dict | None = None, timeout: float | None = None, stage: ErrorStage = 'user_info') → Response[source]
require_association_user(user: UserProtocol | None, *, stage: ErrorStage = 'user_info') → UserProtocol[source]

Require an authenticated local user for an association-only flow.

run_pipeline(pipeline: list[str], pipeline_index=0, *args, **kwargs) → dict[source]
setting(name: str, default=None)[source]

Return setting value from strategy

start() → HttpResponseProtocol[source]
supports_inactive_user = False
title: str | None = None
uses_redirect() → bool[source]

Return True if this provider uses redirect url method, otherwise return false.

validate_association_state(request_state: Any, user: UserProtocol | None = None) → str[source]

Validate and consume authorization state bound to the current user.

validate_partial_pipeline(partial: PartialMixin, user: UserProtocol | None = None) → None[source]

Validate backend-specific requirements before resuming a pipeline.

class social_core.backends.oauth.BaseOAuth1(strategy: BaseStrategy | None = None, redirect_uri: str | None = None)[source]

Bases: OAuthAuth

Consumer based mechanism OAuth authentication, fill the needed parameters to communicate properly with authentication service.

URLs settings:

REQUEST_TOKEN_URL Request token URL

OAUTH_TOKEN_PARAMETER_NAME = 'oauth_token'
REDIRECT_URI_PARAMETER_NAME = 'redirect_uri'
REQUEST_TOKEN_METHOD: Literal['GET', 'POST'] = 'GET'
REQUEST_TOKEN_URL: str = ''
UNATHORIZED_TOKEN_SUFIX = 'unauthorized_token_name'
access_token(token: dict) → dict[str, str][source]

Return request for access token value

auth_complete(*args, **kwargs)[source]

Return user, might be logged in

auth_url() → str[source]

Return redirect url

do_auth(access_token, *args, **kwargs)[source]

Finish the auth process once the access_token was retrieved

get_unauthorized_token()[source]
oauth_auth(token: dict | None = None, oauth_verifier=None, signature_type='AUTH_HEADER', *, stage: Literal['begin', 'callback', 'token_exchange', 'token_validation', 'user_info', 'pipeline', 'refresh', 'disconnect', 'unknown'] = 'callback')[source]
oauth_authorization_request(token)[source]

Generate OAuth request to authorize token.

oauth_request(token: dict, url: str, params=None, method: Literal['GET', 'POST'] = 'GET') → Response[source]

Generate OAuth request, setups callback url

process_error(data, *, stage: Literal['begin', 'callback', 'token_exchange', 'token_validation', 'user_info', 'pipeline', 'refresh', 'disconnect', 'unknown'] = 'callback') → None[source]

Hook to process provider response errors.

Default implementation is a no-op. Backends that can detect provider-specific error payloads should override this method and raise an appropriate exception when needed.

request_token_extra_arguments() → dict[str, str][source]

Return extra arguments needed on request-token process

set_unauthorized_token()[source]
unauthorized_token()[source]

Return request for unauthorized token (first stage)

user_data(access_token: dict, *args, **kwargs) → dict[str, Any] | None[source]

Loads user data from service. Implement in subclass

class social_core.backends.oauth.BaseOAuth2(strategy: BaseStrategy | None = None, redirect_uri: str | None = None)[source]

Bases: OAuthAuth

Base class for OAuth2 providers.

OAuth2 details at:

https://datatracker.ietf.org/doc/html/rfc6749

REDIRECT_STATE = True
REFRESH_TOKEN_METHOD: Literal['GET', 'POST', 'DELETE'] = 'POST'
REFRESH_TOKEN_URL: str | None = None
RESPONSE_TYPE: str | None = 'code'
STATE_PARAMETER = True
USE_BASIC_AUTH = False
auth_complete(*args, **kwargs)[source]

Completes login process, must return user instance

auth_complete_credentials()[source]
auth_complete_params(state=None)[source]
auth_headers() → Mapping[str, str | bytes][source]
auth_params(state: str | None = None) → dict[str, str][source]
auth_url() → str[source]

Return redirect url

do_auth(access_token, *args, **kwargs)[source]

Finish the auth process once the access_token was retrieved

extra_data(user, uid: str, response: dict[str, Any], details: dict[str, Any], pipeline_kwargs: dict[str, Any]) → dict[str, Any][source]

Return access_token, token_type, and extra defined names to store in extra_data field

get_access_token(response: dict[str, Any]) → str[source]

Extract a usable access token before profile lookup or pipeline execution.

process_error(data, *, stage: Literal['begin', 'callback', 'token_exchange', 'token_validation', 'user_info', 'pipeline', 'refresh', 'disconnect', 'unknown'] = 'callback') → None[source]

Hook to process provider response errors.

Default implementation is a no-op. Backends that can detect provider-specific error payloads should override this method and raise an appropriate exception when needed.

process_refresh_token_response(response, *args, **kwargs) → dict[source]
refresh_token(token: str, *args, **kwargs) → dict[source]
refresh_token_auth() → AuthBase | None[source]
refresh_token_params(token: str, *args, **kwargs) → dict[str, str][source]
refresh_token_url()[source]
request_access_token(url: str, method: Literal['GET', 'POST', 'DELETE'] = 'GET', headers: Mapping[str, str | bytes] | None = None, data: dict | None = None, json: dict | None = None, auth: tuple[str, str] | AuthBase | None = None, params: dict | None = None, *, stage: ErrorStage = 'token_exchange') → dict[Any, Any][source]
use_basic_auth() → bool[source]
user_data(access_token: str, *args, **kwargs) → dict[str, Any] | None[source]

Loads user data from service. Implement in subclass

class social_core.backends.oauth.BaseOAuth2PKCE(strategy: BaseStrategy | None = None, redirect_uri: str | None = None)[source]

Bases: BaseOAuth2

Base class for providers using OAuth2 with Proof Key for Code Exchange (PKCE).

OAuth2 details at:

https://datatracker.ietf.org/doc/html/rfc6749

PKCE details at:

https://datatracker.ietf.org/doc/html/rfc7636

DEFAULT_USE_PKCE = True
PKCE_DEFAULT_CODE_CHALLENGE_METHOD = 'S256'
PKCE_DEFAULT_CODE_VERIFIER_LENGTH = 43
auth_complete_params(state=None)[source]
auth_params(state=None)[source]
create_code_verifier()[source]
generate_code_challenge(code_verifier, challenge_method)[source]
get_code_verifier()[source]
class social_core.backends.oauth.OAuthAuth(strategy: BaseStrategy | None = None, redirect_uri: str | None = None)[source]

Bases: BaseAuth

OAuth authentication backend base class.

Settings will be inspected to get more values names that should be stored on extra_data field. The setting name is created following the pattern SOCIAL_AUTH_<uppercase current backend name>_EXTRA_DATA.

access_token is always stored.

URLs settings:

AUTHORIZATION_URL Authorization service url ACCESS_TOKEN_URL Access token URL

ACCESS_TOKEN_METHOD: Literal['GET', 'POST'] = 'POST'
ACCESS_TOKEN_PAYLOAD: Literal['form', 'json'] = 'form'
ACCESS_TOKEN_URL: str = ''
AUTHORIZATION_URL = ''
DEFAULT_SCOPE: list[str] | None = None
ID_KEY = 'id'
REDIRECT_STATE = False
REVOKE_TOKEN_METHOD: Literal['GET', 'POST', 'DELETE'] = 'POST'
REVOKE_TOKEN_URL: str = ''
SCOPE_PARAMETER_NAME = 'scope'
SCOPE_SEPARATOR = ' '
STATE_PARAMETER = False
access_token_url() → str[source]
authorization_url() → str[source]
extra_data(user, uid: str, response: dict[str, Any], details: dict[str, Any], pipeline_kwargs: dict[str, Any]) → dict[str, Any][source]

Return access_token and extra defined names to store in extra_data field

get_access_token_url_format() → dict[str, str][source]
get_authorization_url_format() → dict[str, str][source]
get_or_create_state() → str | None[source]
get_redirect_uri(state: str | None = None) → str[source]

Build redirect with redirect_state parameter.

get_request_state()[source]
get_scope() → list[str][source]

Return list with needed access scope

get_scope_argument()[source]
get_session_state()[source]
process_revoke_token_response(response)[source]
revoke_token(token, uid)[source]
revoke_token_headers(token, uid) → dict[str, Any][source]
revoke_token_params(token, uid) → dict[str, Any][source]
revoke_token_url(token, uid) → str[source]
state_token()[source]

Generate csrf token to include as state parameter.

user_data(access_token, *args, **kwargs) → dict[str, Any] | None[source]

Loads user data from service. Implement in subclass

validate_state()[source]

Validate state value. Raises exception on error, returns state value if valid.

class social_core.backends.open_id.OpenIdAuth(strategy: BaseStrategy | None = None, redirect_uri: str | None = None)[source]

Bases: BaseAuth

Generic OpenID authentication backend

PROTOCOL_ID_KEY = 'identity_url'
URL: str | None = None
USERNAME_KEY = 'username'
auth_complete(*args, **kwargs)[source]

Complete auth process

auth_html()[source]

Return auth HTML returned by service

auth_url()[source]

Return auth URL returned by service

consumer()[source]

Create an OpenID Consumer object for the given Django request.

continue_pipeline(partial)[source]

Continue previous halted pipeline

create_consumer(store=None)[source]
extra_data(user, uid: str, response: dict[str, Any], details: dict[str, Any], pipeline_kwargs: dict[str, Any]) → dict[str, Any][source]

Return defined extra data names to store in extra_data field. Settings will be inspected to get more values names that should be stored on extra_data field. Setting name is created from current backend name (all uppercase) plus _SREG_EXTRA_DATA and _AX_EXTRA_DATA because values can be returned by SimpleRegistration or AttributeExchange schemas.

Both list must be a value name and an alias mapping similar to SREG_ATTR, OLD_AX_ATTRS or AX_SCHEMA_ATTRS

get_ax_attributes() → list[tuple[str, str]][source]
get_consumer_store() → OpenIdStore | None[source]
get_return_to() → str[source]
get_sreg_attributes()[source]
get_user_details(response)[source]

Return user details from an OpenID request

get_user_id(details, response)[source]

Return the protocol-defined identity URL provided by the service.

OpenID identity is asserted as a URL rather than a response mapping field, so the configurable ID_KEY does not apply to this backend.

get_user_id_for_key(details, response, id_key: str)[source]

Return the asserted identity URL or an explicitly selected profile field.

name = 'openid'
openid_request(params: dict[str, str] | None = None)[source]

Return openid request

openid_url()[source]

Return service provider URL. This base class is generic accepting a POST parameter that specifies provider URL.

process_error(data, *, stage: Literal['begin', 'callback', 'token_exchange', 'token_validation', 'user_info', 'pipeline', 'refresh', 'disconnect', 'unknown'] = 'callback') → None[source]

Hook to process provider response errors.

Default implementation is a no-op. Backends that can detect provider-specific error payloads should override this method and raise an appropriate exception when needed.

setup_request(params=None)[source]

Setup request

title = 'OpenID'
trust_root()[source]

Return trust-root option

uses_redirect()[source]

Return true if openid request will be handled with redirect or HTML content will be returned.

values_from_response(response, sreg_names=None, ax_names=None)[source]

Return values from SimpleRegistration response or AttributeExchange response if present.

@sreg_names and @ax_names must be a list of name and aliases for such name. The alias will be used as mapping key.

class social_core.backends.open_id_connect.OpenIdConnectAssociation(handle, secret='', issued=0, lifetime=0, assoc_type='')[source]

Bases: object

Use Association model to save the nonce by force.

class social_core.backends.open_id_connect.OpenIdConnectAuth(strategy: BaseStrategy | None = None, redirect_uri: str | None = None)[source]

Bases: BaseOAuth2PKCE

Base class for Open ID Connect backends. Currently only the code response type is supported.

It can also be directly instantiated as a generic OIDC backend. To use it you will need to set at minimum:

SOCIAL_AUTH_OIDC_OIDC_ENDPOINT = ‘https://…..’ # endpoint without /.well-known/openid-configuration SOCIAL_AUTH_OIDC_KEY = ‘<client_id>’ SOCIAL_AUTH_OIDC_SECRET = ‘<client_secret>’ SOCIAL_AUTH_OIDC_USE_PKCE = True # optional, enables PKCE for this backend

ACCESS_TOKEN_URL = ''
ACR_VALUES: str | None = None
AUTHORIZATION_URL = ''
CUSTOM_AT_HASH_ALGO: str | None = None
DEFAULT_SCOPE = ['openid', 'profile', 'email']
DEFAULT_USE_PKCE = False
DISPLAY: str | None = None
EMAIL_KEY = 'email'
EXTRA_DATA = ['id_token', 'refresh_token', ('sub', 'id')]
FIRST_NAME_KEY = 'given_name'
FULLNAME_KEY = 'name'
ID_KEY = 'sub'
ID_TOKEN_HINT: str | None = None
ID_TOKEN_ISSUER = ''
ID_TOKEN_MAX_AGE = 600
JWKS_URI = ''
JWT_ALGORITHMS = ['RS256']
JWT_DECODE_OPTIONS: Options = {}
JWT_LEEWAY: float = 1.0
LAST_NAME_KEY = 'family_name'
LOGIN_HINT: str | None = None
MAX_AGE: int | None = None
NONCE_LIFETIME = 1800
OIDC_ENDPOINT: str | None = None
PKCE_DEFAULT_CODE_CHALLENGE_METHOD = 'S256'
PROMPT: str | None = None
REDIRECT_STATE = False
REVOKE_TOKEN_METHOD: Literal['GET', 'POST', 'DELETE'] = 'GET'
REVOKE_TOKEN_URL = ''
TOKEN_ENDPOINT_AUTH_METHOD = ''
UI_LOCALES: str | None = None
USERINFO_URL = ''
USERNAME_KEY = 'preferred_username'
USE_NONCE = True
VALIDATE_AT_HASH: bool = True
access_token_url() → str[source]
auth_params(state=None)[source]

Return extra arguments needed on auth process.

authorization_url() → str[source]
static calc_at_hash(access_token, algorithm, custom_at_hash_algo: str | None = None)[source]

Calculates “at_hash” claim which is not done by pyjwt. Custom “at_hash” algorithm is used for non-standard token.

See https://pyjwt.readthedocs.io/en/stable/usage.html#oidc-login-flow See https://github.com/python-social-auth/social-core/issues/1306

continue_pipeline(partial: PartialMixin) → UserProtocol | HttpResponseProtocol | None[source]

Continue previous halted pipeline

decode_and_validate_id_token(id_token, access_token)[source]

Validate an ID token’s signature and self-contained claims.

extra_data(user, uid: str, response: dict[str, Any], details: dict[str, Any], pipeline_kwargs: dict[str, Any]) → dict[str, Any][source]

Return access_token, token_type, and extra defined names to store in extra_data field

find_valid_key(id_token)[source]
get_and_store_nonce(url, state)[source]
get_jwks_keys(*args, **kwargs)
get_nonce(nonce)[source]
get_remote_jwks_keys()[source]
get_setting_config(setting_name: str, oidc_name: str, default: str, *, stage: Literal['begin', 'callback', 'token_exchange', 'token_validation', 'user_info', 'pipeline', 'refresh', 'disconnect', 'unknown'] = 'begin') → str[source]
get_user_details(response)[source]

Return user details from the UserInfo response or ID token.

get_user_groups(response) → list[str] | None[source]

Return normalized external memberships, or None when disabled.

get_user_id(details, response)[source]

Return a unique ID for the current user, by default from server response or details.

static id_token_audiences(audience) → set[str][source]
id_token_issuer() → str[source]
jwks_uri() → str[source]
name = 'oidc'
oidc_config(*args, **kwargs)
oidc_endpoint() → str[source]
pipeline(pipeline, pipeline_index: int = 0, *args, **kwargs) → UserProtocol | HttpResponseProtocol | None[source]
process_refresh_token_response(response, *args, **kwargs) → dict[source]
remove_nonce(nonce_id) → None[source]
request_access_token(url: str, method: Literal['GET', 'POST', 'DELETE'] = 'GET', headers: Mapping[str, str | bytes] | None = None, data: dict | None = None, json: dict | None = None, auth: tuple[str, str] | AuthBase | None = None, params: dict | None = None, *, stage: ErrorStage = 'token_exchange') → dict[Any, Any][source]

Retrieve the access token. Also, validate the id_token and store it (temporarily).

revoke_token_url(token, uid) → str[source]
title = 'OpenID Connect'
use_basic_auth() → bool[source]
user_data(access_token: str, *args, **kwargs) → dict[str, Any] | None[source]

Loads user data from service. Implement in subclass

userinfo_url() → str[source]
validate_and_return_id_token(id_token, access_token)[source]

Validates the id_token according to the steps at http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation.

validate_and_return_refresh_id_token(id_token, access_token)[source]

Validate an ID token returned by a refresh request.

validate_at_hash(claims, access_token, key)[source]

Validate the ‘at_hash’ claim according to OpenID Connect specs.

See: https://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken

validate_authorized_party(claims, client_id: str) → None[source]

Validate the client authorized to use the ID token.

validate_claims(id_token) → None[source]
validate_refresh_id_token_claims(previous, current) → None[source]

Validate identity continuity for an ID token refresh.

validate_required_id_token_claims(claims) → None[source]

Validate claims required in every ID token.

validate_temporal_claims(id_token) → None[source]
validate_userinfo_sub(userinfo: dict[str, Any] | None) → dict[str, Any] | None[source]

Validate that UserInfo belongs to the validated ID token subject.

Pipeline

social_core.pipeline.social_auth.associate_by_email(backend: BaseAuth, details, user: UserProtocol | None = None, *args, **kwargs)[source]

Associate current auth with a user with the same email address in the DB.

This pipeline entry is not 100% secure unless you know that the providers enabled enforce email verification on their side, otherwise a user can attempt to take over another user account by using the same (not validated) email address on some provider. This pipeline entry is disabled by default.

social_core.pipeline.social_auth.associate_user(backend: BaseAuth, uid, user: UserProtocol | None = None, social=None, *args, id_key='', legacy_uids=(), **kwargs)[source]
social_core.pipeline.social_auth.auth_allowed(backend: BaseAuth, details, response, *args, **kwargs) → None[source]
social_core.pipeline.social_auth.load_extra_data(backend: BaseAuth, details, response, uid, user: UserProtocol | None = None, *args, **kwargs) → None[source]
social_core.pipeline.social_auth.social_details(backend: BaseAuth, details, response, *args, **kwargs)[source]
social_core.pipeline.social_auth.social_names(backend: BaseAuth, details, *args, **kwargs)[source]

Populate missing full or component names using provider details.

social_core.pipeline.social_auth.social_uid(backend: BaseAuth, details, response, *args, **kwargs)[source]
social_core.pipeline.social_auth.social_user(backend: BaseAuth, uid, user: UserProtocol | None = None, *args, id_key='', legacy_uids=(), **kwargs)[source]
social_core.pipeline.user.create_user(strategy: BaseStrategy, details, backend: BaseAuth, user: UserProtocol | None = None, *args, **kwargs)[source]
social_core.pipeline.user.get_username(strategy: BaseStrategy, details, backend: BaseAuth, user: UserProtocol | None = None, *args, **kwargs)[source]
social_core.pipeline.user.sync_groups(strategy, backend, response, user=None, groups=None, **kwargs) → None[source]

Synchronize local memberships through the application’s strategy.

social_core.pipeline.user.user_details(strategy: BaseStrategy, details, backend: BaseAuth | None, user: UserProtocol | None = None, *args, **kwargs) → None[source]

Update user details using data from provider.

social_core.pipeline.mail.mail_validation(backend: BaseAuth, details, is_new=False, *args, **kwargs)[source]

Framework integration

class social_core.strategy.BaseStrategy(storage: type[BaseStorage] | None = None, tpl: type[BaseTemplateStrategy] | None = None)[source]

Bases: object

ALLOWED_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
DEFAULT_TEMPLATE_STRATEGY

alias of BaseTemplateStrategy

SESSION_SAVE_KEY = 'psa_session_id'
absolute_uri(path: str | None = None) → str[source]
authenticate(backend: BaseAuth, *args, **kwargs) → UserProtocol | HttpResponseProtocol | None[source]

Trigger the authentication mechanism tied to the current framework

build_absolute_uri(path: str | None = None) → str[source]

Build absolute URI with given (optional) path

clean_authenticate_args(*args, **kwargs)[source]

Take authenticate arguments and return a “cleaned” version of them

clean_partial_pipeline(token) → None[source]
create_user(*args, **kwargs)[source]
from_session_value(val)[source]
get_backend(name: str, redirect_uri: str | None = None, **kwargs) → BaseAuth[source]

Return a configured backend instance

get_backend_class(name: str) → type[BaseAuth][source]

Return a configured backend class

get_backends() → list[str][source]

Return configured backends

get_disconnect_pipeline(backend: BaseAuth | None = None) → list[str][source]
get_language() → str[source]

Return current language

get_pipeline(backend: BaseAuth | None = None) → list[str][source]
get_request_data(merge: bool = True) → dict[str, Any][source]

Return data from the current framework request (POST or GET).

get_session_id() → str | None[source]

Return session ID to be used by restore_session.

get_setting(name: str)[source]

Return value for given setting name

get_storage(*, stage: ErrorStage) → type[BaseStorage][source]

Resolve storage while reporting failures at the calling operation.

get_user(*args, **kwargs)[source]
html(content: str) → HttpResponseProtocol[source]

Return HTTP response with given content

openid_session_dict(name: str) → OpenIdSessionWrapper[source]
openid_store() → OpenIdStore[source]
partial_load(token: str) → PartialMixin | None[source]
partial_pipeline_external_resume_confirmation(backend: BaseAuth, partial: PartialMixin, request_data: dict[str, Any]) → HttpResponseProtocol | None[source]
partial_pipeline_external_resume_confirmed(backend: BaseAuth, request_data: dict[str, Any]) → bool[source]
pipeline_request_data(data: Mapping[str, Any] | None) → Iterator[None][source]

Scope effective request data to one pipeline execution.

random_string(length: int = 12, chars: str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') → str[source]
redirect(url: str) → HttpResponseProtocol[source]

Return a response redirect to the given URL

render_html(tpl: str | None = None, html: str | None = None, context: dict[str, Any] | None = None) → str[source]

Render given template or raw html with given context

request_data(merge: bool = True) → dict[str, Any][source]

Return effective pipeline data, or data from the current request.

During a partial resume, merge does not change the replayed mapping. Use get_request_data(), request_get(), or request_post() to read the current framework request without replayed data.

request_get()[source]

Request GET data

request_host() → str[source]

Return current host value

request_is_secure() → bool[source]

Is the request using HTTPS?

request_path() → str[source]

path of the current request

request_port() → int[source]

Port in use for this request

request_post()[source]

Request POST data

restore_session(session_id: str, kwargs: dict[str, Any]) → None[source]

Restores session and updates kwargs to match it.

This is only called if get_session_id returns a value.

send_email_validation(backend: BaseAuth, email: str, partial_token: str | None = None) → CodeMixin[source]
session_get(name: str, default=None)[source]

Return session value for given key

session_pop(name: str)[source]

Pop session value for given key

session_set(name: str, value)[source]

Set session value for given key

session_setdefault(name: str, value)[source]
setting(name: str, default=None, backend: BaseAuth | None = None)[source]
property storage: type[BaseStorage]
sync_user_groups(user, groups: list[str] | None, *, backend: BaseAuth, response, **kwargs) → None[source]

Override to apply configured external memberships to local groups.

to_session_value(val)[source]
validate_email(email: str, code: str) → bool[source]
class social_core.strategy.BaseTemplateStrategy(strategy)[source]

Bases: object

render(tpl: str | None = None, html: str | None = None, context: dict[str, Any] | None = None) → str[source]
render_string(html: str, context: dict[str, Any] | None) → str[source]
render_template(tpl: str, context: dict[str, Any] | None) → str[source]
class social_core.strategy.HttpResponseProtocol(*args, **kwargs)[source]

Bases: Protocol

property url: str

Models mixins for Social Auth

class social_core.storage.AssociationMixin[source]

Bases: object

OpenId account association

assoc_type = ''
classmethod get(server_url: str | None = None, handle: str | None = None)[source]

Get an Association instance

handle = ''
is_expired(now: int | None = None) → bool[source]

Return whether the association’s lifetime has elapsed.

issued = 0
lifetime = 0
classmethod oids(server_url, handle=None)[source]
classmethod openid_association(assoc)[source]
classmethod remove(ids_to_delete)[source]

Remove an Association instance

secret: str | bytes = ''
server_url = ''
classmethod store(server_url, association)[source]

Create an Association instance

class social_core.storage.BaseStorage[source]

Bases: object

association

alias of AssociationMixin

code

alias of CodeMixin

classmethod is_integrity_error(exception) → bool[source]

Check if given exception flags an integrity error in the DB

nonce

alias of NonceMixin

partial

alias of PartialMixin

user

alias of UserMixin

class social_core.storage.CodeMixin[source]

Bases: object

code = ''
email = ''
classmethod generate_code()[source]
classmethod get_code(code)[source]
is_expired(seconds: int) → bool[source]

Return whether the code has reached its lifetime, or has no timestamp.

classmethod make_code(email: str) → CodeMixin[source]
abstractmethod save()[source]
timestamp: datetime | None = None
verified = False
verify() → None[source]
class social_core.storage.NonceMixin[source]

Bases: object

One use numbers

classmethod delete(nonce)[source]

Delete a Nonce instance

classmethod get(server_url: str, salt: str)[source]

Retrieve a Nonce instance

salt = ''
server_url = ''
timestamp = 0
classmethod use(server_url: str, timestamp, salt: str)[source]

Create a Nonce instance

class social_core.storage.PartialMixin[source]

Bases: object

property args
backend = ''
data: dict[str, Any] = {}
classmethod destroy(token: str)[source]
extend_kwargs(values) → None[source]
classmethod generate_token() → str[source]
property kwargs
classmethod load(token: str) → PartialMixin | None[source]
next_step: int
property pipeline_type: str

Legacy partials may resume authentication, but never disconnect.

classmethod prepare(backend: str, next_step: int, data: dict[str, Any]) → PartialMixin[source]
property request_data: Mapping[str, Any] | None

Effective data for a resume, including legacy partial snapshots.

abstractmethod save()[source]
classmethod store(partial: PartialMixin) → PartialMixin[source]
token = ''
class social_core.storage.PipelineUserProtocol(*args, **kwargs)[source]

Bases: UserProtocol, Protocol

is_new: bool
social_user: UserMixin | None
class social_core.storage.UserMixin[source]

Bases: object

ACCESS_TOKEN_EXPIRED_THRESHOLD = 5
property access_token: str | None

Return access_token stored in extra_data or None

access_token_expired()[source]

Return true / false if access token is already expired

classmethod allowed_to_disconnect(user: UserProtocol, backend_name: str, association_id=None) → bool[source]

Return if it’s safe to disconnect the social account for the given user

classmethod changed(user: UserProtocol) → None[source]

The given user instance is ready to be saved

classmethod clean_username(value: str) → str[source]

Clean username removing any unsupported character

classmethod create_social_auth(user: UserProtocol, uid: str, provider: str, id_key: str = '')[source]

Create a UserSocialAuth instance for given user

classmethod create_user(*args, **kwargs)[source]

Create a user instance

classmethod disconnect(entry)[source]

Disconnect the social account for the given user

expiration_datetime()[source]
expiration_timedelta() → timedelta | None[source]

Return provider session live seconds.

Returns a timedelta ready to use with session.set_expiry(). If provider returns a timestamp instead of session seconds to live, the timedelta is inferred from current time (using UTC timezone).

Handles three types of expiration data: - expires_on: Always treated as absolute timestamp - expires_in: Always treated as relative seconds from auth_time - expires: Uses heuristic (>63072000 = 2 years) to distinguish timestamp vs relative

extra_data: dict[str, Any]
get_access_token(strategy: BaseStrategy) → str | None[source]

Returns a valid access token.

get_backend(strategy: BaseStrategy) → type[BaseAuth][source]
get_backend_instance(strategy: BaseStrategy) → BaseAuth | None[source]
classmethod get_social_auth(provider: str, uid: str, id_key: str | None = None)[source]

Return UserSocialAuth for given provider and uid

classmethod get_social_auth_by_extra_data(provider: str, key: str, value: str, id_key: str = '')[source]

Return an unambiguous association matching stored provider data.

classmethod get_social_auth_for_user(user: UserProtocol, provider: str | None = None, id: int | None = None)[source]

Return all the UserSocialAuth instances for given user

classmethod get_user(pk)[source]

Return user instance for given id

classmethod get_username(user: UserProtocol) → str[source]

Return the username for given user

classmethod get_users_by_email(email: str)[source]

Return users instances for given email address

id_key = ''
classmethod migrate_social_auth(social, uid: str, id_key: str)[source]

Atomically replace an association’s identifier and identifier key.

provider = ''
refresh_token(strategy: BaseStrategy, *args, **kwargs) → None[source]

Renew stored credentials using the backend’s selected token.

Missing renewal credentials require reauthentication only when the stored access token is known to have expired. Otherwise no request is sent. Backends without a refresh method are left unchanged.

abstractmethod save()[source]
set_extra_data(extra_data: dict[str, Any] | None = None) → bool[source]
uid: str
user: UserProtocol
classmethod user_exists(*args, **kwargs) → bool[source]

Return True/False if a User instance exists with the given arguments. Arguments are directly passed to filter() manager method.

classmethod user_model() → type[UserProtocol][source]

Return the user model

classmethod username_max_length() → int[source]

Return the max length for username

class social_core.storage.UserProtocol(*args, **kwargs)[source]

Bases: Protocol

property id: int
property is_active: bool | Callable[[], bool]
property is_authenticated: bool | Callable[[], bool]
property username: str

Errors and utilities

Authentication failures with stable, framework-independent recovery metadata.

exception social_core.exceptions.AuthAssociationError(backend: BaseAuth | None = None, *details: object, code: str | None = None, source: ErrorSource | None = None, stage: ErrorStage = 'unknown', recovery: RecoveryAction | None = None, parameter: str | None = None, claim: str | None = None, provider_code: str | int | None = None, status_code: int | None = None, retry_after: str | None = None, context: Mapping[str, Any] | None = None)[source]

Bases: AuthException

A local account or stored authentication identity conflicts.

default_code = 'identity_in_use'
exception social_core.exceptions.AuthCanceled(backend: BaseAuth | None = None, *details: object, code: str | None = None, source: ErrorSource | None = None, stage: ErrorStage = 'unknown', recovery: RecoveryAction | None = None, parameter: str | None = None, claim: str | None = None, provider_code: str | int | None = None, status_code: int | None = None, retry_after: str | None = None, context: Mapping[str, Any] | None = None)[source]

Bases: AuthException

Authorization was explicitly declined or canceled.

default_code = 'authorization_declined'
exception social_core.exceptions.AuthConfigurationError(backend: BaseAuth | None = None, *details: object, code: str | None = None, source: ErrorSource | None = None, stage: ErrorStage = 'unknown', recovery: RecoveryAction | None = None, parameter: str | None = None, claim: str | None = None, provider_code: str | int | None = None, status_code: int | None = None, retry_after: str | None = None, context: Mapping[str, Any] | None = None)[source]

Bases: SocialAuthBaseException

The integration needs configuration or implementation changes.

default_code = 'invalid_setting'
exception social_core.exceptions.AuthCredentialError(backend: BaseAuth | None = None, *details: object, code: str | None = None, source: ErrorSource | None = None, stage: ErrorStage = 'unknown', recovery: RecoveryAction | None = None, parameter: str | None = None, claim: str | None = None, provider_code: str | int | None = None, status_code: int | None = None, retry_after: str | None = None, context: Mapping[str, Any] | None = None)[source]

Bases: AuthException

Credentials were rejected or another provider login is required.

default_code = 'credential_rejected'
exception social_core.exceptions.AuthException(backend: BaseAuth | None = None, *details: object, code: str | None = None, source: ErrorSource | None = None, stage: ErrorStage = 'unknown', recovery: RecoveryAction | None = None, parameter: str | None = None, claim: str | None = None, provider_code: str | int | None = None, status_code: int | None = None, retry_after: str | None = None, context: Mapping[str, Any] | None = None)[source]

Bases: SocialAuthBaseException

Broad catch boundary for authentication-flow failures.

exception social_core.exceptions.AuthInputError(backend: BaseAuth | None = None, *details: object, code: str | None = None, source: ErrorSource | None = None, stage: ErrorStage = 'unknown', recovery: RecoveryAction | None = None, parameter: str | None = None, claim: str | None = None, provider_code: str | int | None = None, status_code: int | None = None, retry_after: str | None = None, context: Mapping[str, Any] | None = None)[source]

Bases: AuthException

The application or browser supplied missing or invalid input.

default_code = 'invalid_parameter'
exception social_core.exceptions.AuthPolicyError(backend: BaseAuth | None = None, *details: object, code: str | None = None, source: ErrorSource | None = None, stage: ErrorStage = 'unknown', recovery: RecoveryAction | None = None, parameter: str | None = None, claim: str | None = None, provider_code: str | int | None = None, status_code: int | None = None, retry_after: str | None = None, context: Mapping[str, Any] | None = None)[source]

Bases: AuthException

A local authentication or disconnect policy rejected the operation.

default_code = 'authentication_disallowed'
exception social_core.exceptions.AuthProviderError(backend: BaseAuth | None = None, *details: object, code: str | None = None, source: ErrorSource | None = None, stage: ErrorStage = 'unknown', recovery: RecoveryAction | None = None, parameter: str | None = None, claim: str | None = None, provider_code: str | int | None = None, status_code: int | None = None, retry_after: str | None = None, context: Mapping[str, Any] | None = None)[source]

Bases: AuthException

A provider request failed at the transport or HTTP boundary.

default_code = 'http_error'
exception social_core.exceptions.AuthResponseError(backend: BaseAuth | None = None, *details: object, code: str | None = None, source: ErrorSource | None = None, stage: ErrorStage = 'unknown', recovery: RecoveryAction | None = None, parameter: str | None = None, claim: str | None = None, provider_code: str | int | None = None, status_code: int | None = None, retry_after: str | None = None, context: Mapping[str, Any] | None = None)[source]

Bases: AuthException

A provider response cannot be parsed or validated.

default_code = 'malformed_response'
exception social_core.exceptions.AuthSessionError(backend: BaseAuth | None = None, *details: object, code: str | None = None, source: ErrorSource | None = None, stage: ErrorStage = 'unknown', recovery: RecoveryAction | None = None, parameter: str | None = None, claim: str | None = None, provider_code: str | int | None = None, status_code: int | None = None, retry_after: str | None = None, context: Mapping[str, Any] | None = None)[source]

Bases: AuthException

Authentication cannot be bound to its initiating session or user.

default_code = 'session_context_missing'
exception social_core.exceptions.AuthUnknownError(backend: BaseAuth | None = None, *details: object, code: str | None = None, source: ErrorSource | None = None, stage: ErrorStage = 'unknown', recovery: RecoveryAction | None = None, parameter: str | None = None, claim: str | None = None, provider_code: str | int | None = None, status_code: int | None = None, retry_after: str | None = None, context: Mapping[str, Any] | None = None)[source]

Bases: AuthException

The authentication failure has no known structured classification.

exception social_core.exceptions.SocialAuthBaseException(backend: BaseAuth | None = None, *details: object, code: str | None = None, source: ErrorSource | None = None, stage: ErrorStage = 'unknown', recovery: RecoveryAction | None = None, parameter: str | None = None, claim: str | None = None, provider_code: str | int | None = None, status_code: int | None = None, retry_after: str | None = None, context: Mapping[str, Any] | None = None)[source]

Bases: ValueError

Broad catch boundary for social-auth failures, including configuration.

default_code = 'unknown_error'
public_metadata() → dict[str, str][source]

Return non-identifying fields for client transports.

source: Literal['configuration', 'request', 'session', 'provider_response', 'local_policy', 'storage', 'unknown']
stage: Literal['begin', 'callback', 'token_exchange', 'token_validation', 'user_info', 'pipeline', 'refresh', 'disconnect', 'unknown']
class social_core.utils.PartialPipelineResult(partial: 'PartialMixin | None' = None, response: 'HttpResponseProtocol | None' = None, halt: 'bool' = False)[source]
halt: bool = False
partial: PartialMixin | None = None
response: HttpResponseProtocol | None = None
class social_core.utils.PartialPipelineSelection(token: 'str | None' = None, owns_token: 'bool' = False, pending_resume: 'bool' = False)[source]
owns_token: bool = False
pending_resume: bool = False
token: str | None = None
social_core.utils.append_slash(url: str) → str[source]

Make sure we append a slash at the end of the URL otherwise we have issues with urljoin Example: >>> urlparse.urljoin(’http://www.example.com/api/v3’, ‘user/1/’) ‘http://www.example.com/api/user/1/’

social_core.utils.build_absolute_uri(host_url: str, path: str | None = None) → str[source]

Build absolute URI with given (optional) path

class social_core.utils.cache(ttl: int)[source]

Cache decorator that caches the return value of a method for a specified time.

It maintains a cache per class and method arguments, so subclasses have a different cache entry for the same cached method.

Call method.invalidate() to clear all entries, or method.invalidate(instance, *args, **kwargs) to clear one entry. Call method.refresh(instance, *args, **kwargs) to replace one entry only after the underlying method succeeds. Failed refreshes propagate their exception and preserve the existing value and expiry time.

cache: dict[tuple[type, tuple[Any, ...], tuple[tuple[str, Any], ...]], Any]
social_core.utils.constant_time_compare(val1: str | bytes, val2: str | bytes) → bool[source]

Compare two values and prevent timing attacks for cryptographic use.

social_core.utils.drop_lists(value)[source]
social_core.utils.first(func, items)[source]

Return the first item in the list for what func returns True

social_core.utils.get_allowed_redirect_schemes(backend: BaseAuth) → set[str][source]
social_core.utils.get_querystring(url: str)[source]
social_core.utils.get_strategy(strategy: str, storage: str, *args, **kwargs) → BaseStrategy[source]
social_core.utils.handle_http_errors(func)[source]

Normalize raw HTTP errors from integrations outside BaseAuth.request.

social_core.utils.http_error(backend: BaseAuth, error: requests.HTTPError, *, stage: ErrorStage = 'user_info') → SocialAuthBaseException[source]

Normalize a Requests HTTP failure, including errors without responses.

social_core.utils.is_private_use_redirect(value: str | None, allowed_schemes: Collection[str] | None = None) → bool[source]

Whether value uses a non-web scheme that has been explicitly allowed.

URI construction helpers such as build_absolute_uri only preserve http and https, so callers must check this before turning a redirect candidate into an absolute URI.

social_core.utils.is_url(value: str | None, allowed_schemes: Collection[str] | None = None) → bool[source]
social_core.utils.module_member(name)[source]
social_core.utils.normalize_redirect_schemes(schemes: Collection[str]) → set[str][source]

URI schemes are case-insensitive, and urlparse lowercases them.

social_core.utils.normalize_user_names(fullname: str | None = '', first_name: str | None = '', last_name: str | None = '', *, firstlast_from_full: bool = True, full_from_firstlast: bool = True) → tuple[str, str, str][source]

Fill missing name representations without replacing supplied names.

social_core.utils.parse_qs(value)[source]

Like urlparse.parse_qs but transform list values to single items

social_core.utils.partial_pipeline_data(backend: BaseAuth, user: UserProtocol | None = None, partial_token: str | None = None, *args, **kwargs) → PartialMixin | None[source]
social_core.utils.partial_pipeline_result(backend: BaseAuth, user: UserProtocol | None = None, partial_token: str | None = None, *args, pipeline_type: str = 'authentication', **kwargs) → PartialPipelineResult[source]
social_core.utils.provider_error(backend: BaseAuth, data: object, *, stage: ErrorStage = 'callback', status_code: int | None = None, retry_after: str | None = None) → SocialAuthBaseException | None[source]

Classify structured protocol errors without inspecting descriptions.

social_core.utils.sanitize_redirect(hosts: list[str], redirect_to: str | Any, allowed_schemes: Collection[str] | None = None) → str | None[source]

Given a list of hostnames and an untrusted URL to redirect to, this method tests it to make sure it isn’t garbage/harmful and returns it, else returns None, similar as how’s it done on django.contrib.auth.views.

allowed_schemes defaults to http and https. Deployments that need to hand control back to a native application can add a private-use URI scheme (RFC 8252) through the ALLOWED_REDIRECT_SCHEMES setting.

social_core.utils.setting_name(*names: str) → str[source]
social_core.utils.setting_url(backend: BaseAuth, *names: str | None) → str | None[source]
social_core.utils.slugify(value)[source]

Converts to lowercase, removes non-word characters (alphanumerics and underscores) and converts spaces to hyphens. Also strips leading and trailing whitespace.

social_core.utils.to_setting_name(*names: str) → str[source]
social_core.utils.url_add_parameters(url: str, params: dict[str, str] | None, _unquote_query: bool = False) → str[source]

Adds parameters to URL, parameter will be repeated if already present

social_core.utils.user_agent() → str[source]

Builds a simple User-Agent string to send in requests

social_core.utils.user_is_active(user: UserProtocol | None) → bool[source]
social_core.utils.user_is_authenticated(user: UserProtocol | None) → bool[source]
social_core.utils.wrap_access_token_error(backend: BaseAuth, *, stage: ErrorStage = 'token_exchange')[source]

Normalize token request HTTP errors without guessing their cause.