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:
objectA authentication backend that authenticates the user based on the provider response.
Set
ASSOCIATION_ONLYto connect provider access to an authenticated local user without updating their profile. Browser flows must start throughdo_auth(user=...)and validate callbacks withvalidate_association_state()before processing provider credentials. Authentication and disconnect partials remain bound to that local user.- ASSOCIATION_ONLY = False¶
- GET_ALL_EXTRA_DATA = False¶
- REQUIRES_EMAIL_VALIDATION = 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.
- 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
- 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_setting(name: str, response, default=None)[source]¶
Resolve group configuration for this provider (or a SAML IdP).
- 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_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:
usernameUsername, if any.
emailUser email, if any.
fullnameUser full name, if any.
first_nameUser first name, if any.
last_nameUser 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.
- name = ''¶
- pipeline(pipeline, pipeline_index: int = 0, *args, **kwargs) → UserProtocol | HttpResponseProtocol | None[source]¶
- 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.
- start() → HttpResponseProtocol[source]¶
- supports_inactive_user = False¶
- 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:
OAuthAuthConsumer 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'¶
- UNATHORIZED_TOKEN_SUFIX = 'unauthorized_token_name'¶
- do_auth(access_token, *args, **kwargs)[source]¶
Finish the auth process once the access_token was retrieved
- 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_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.
- class social_core.backends.oauth.BaseOAuth2(strategy: BaseStrategy | None = None, redirect_uri: str | None = None)[source]¶
Bases:
OAuthAuthBase class for OAuth2 providers.
- OAuth2 details at:
- REDIRECT_STATE = True¶
- REFRESH_TOKEN_METHOD: Literal['GET', 'POST', 'DELETE'] = 'POST'¶
- STATE_PARAMETER = True¶
- USE_BASIC_AUTH = False¶
- 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.
- 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]¶
- class social_core.backends.oauth.BaseOAuth2PKCE(strategy: BaseStrategy | None = None, redirect_uri: str | None = None)[source]¶
Bases:
BaseOAuth2Base class for providers using OAuth2 with Proof Key for Code Exchange (PKCE).
- OAuth2 details at:
- PKCE details at:
- DEFAULT_USE_PKCE = True¶
- PKCE_DEFAULT_CODE_CHALLENGE_METHOD = 'S256'¶
- PKCE_DEFAULT_CODE_VERIFIER_LENGTH = 43¶
- class social_core.backends.oauth.OAuthAuth(strategy: BaseStrategy | None = None, redirect_uri: str | None = None)[source]¶
Bases:
BaseAuthOAuth 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'¶
- AUTHORIZATION_URL = ''¶
- ID_KEY = 'id'¶
- REDIRECT_STATE = False¶
- REVOKE_TOKEN_METHOD: Literal['GET', 'POST', 'DELETE'] = 'POST'¶
- SCOPE_PARAMETER_NAME = 'scope'¶
- SCOPE_SEPARATOR = ' '¶
- STATE_PARAMETER = False¶
- 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_redirect_uri(state: str | None = None) → str[source]¶
Build redirect with redirect_state parameter.
- class social_core.backends.open_id.OpenIdAuth(strategy: BaseStrategy | None = None, redirect_uri: str | None = None)[source]¶
Bases:
BaseAuthGeneric OpenID authentication backend
- PROTOCOL_ID_KEY = 'identity_url'¶
- USERNAME_KEY = 'username'¶
- 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_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_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.
- title = 'OpenID'¶
- class social_core.backends.open_id_connect.OpenIdConnectAssociation(handle, secret='', issued=0, lifetime=0, assoc_type='')[source]¶
Bases:
objectUse 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:
BaseOAuth2PKCEBase 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 = ''¶
- AUTHORIZATION_URL = ''¶
- DEFAULT_SCOPE = ['openid', 'profile', 'email']¶
- DEFAULT_USE_PKCE = False¶
- EMAIL_KEY = 'email'¶
- EXTRA_DATA = ['id_token', 'refresh_token', ('sub', 'id')]¶
- FIRST_NAME_KEY = 'given_name'¶
- FULLNAME_KEY = 'name'¶
- ID_KEY = 'sub'¶
- ID_TOKEN_ISSUER = ''¶
- ID_TOKEN_MAX_AGE = 600¶
- JWKS_URI = ''¶
- JWT_ALGORITHMS = ['RS256']¶
- JWT_DECODE_OPTIONS: Options = {}¶
- LAST_NAME_KEY = 'family_name'¶
- NONCE_LIFETIME = 1800¶
- PKCE_DEFAULT_CODE_CHALLENGE_METHOD = 'S256'¶
- REDIRECT_STATE = False¶
- REVOKE_TOKEN_METHOD: Literal['GET', 'POST', 'DELETE'] = 'GET'¶
- REVOKE_TOKEN_URL = ''¶
- TOKEN_ENDPOINT_AUTH_METHOD = ''¶
- USERINFO_URL = ''¶
- USERNAME_KEY = 'preferred_username'¶
- USE_NONCE = True¶
- 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
- get_jwks_keys(*args, **kwargs)¶
- 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_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.
- name = 'oidc'¶
- oidc_config(*args, **kwargs)¶
- pipeline(pipeline, pipeline_index: int = 0, *args, **kwargs) → UserProtocol | HttpResponseProtocol | 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).
- title = 'OpenID Connect'¶
- user_data(access_token: str, *args, **kwargs) → dict[str, Any] | None[source]¶
Loads user data from service. Implement in subclass
- 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_refresh_id_token_claims(previous, current) → None[source]¶
Validate identity continuity for an ID token refresh.
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.
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'¶
- 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
- get_backend(name: str, redirect_uri: str | None = None, **kwargs) → BaseAuth[source]¶
Return a configured backend instance
- get_request_data(merge: bool = True) → dict[str, Any][source]¶
Return data from the current framework request (POST or GET).
- get_storage(*, stage: ErrorStage) → type[BaseStorage][source]¶
Resolve storage while reporting failures at the calling operation.
- html(content: str) → HttpResponseProtocol[source]¶
Return HTTP response with given content
- 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.
- 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]¶
- property storage: type[BaseStorage]¶
- class social_core.strategy.BaseTemplateStrategy(strategy)[source]¶
Bases:
object
Models mixins for Social Auth
- class social_core.storage.AssociationMixin[source]¶
Bases:
objectOpenId 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¶
- server_url = ''¶
- class social_core.storage.BaseStorage[source]¶
Bases:
object- association¶
alias of
AssociationMixin
- 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
- class social_core.storage.CodeMixin[source]¶
Bases:
object- code = ''¶
- email = ''¶
- is_expired(seconds: int) → bool[source]¶
Return whether the code has reached its lifetime, or has no timestamp.
- verified = False¶
- class social_core.storage.NonceMixin[source]¶
Bases:
objectOne use numbers
- salt = ''¶
- server_url = ''¶
- timestamp = 0¶
- class social_core.storage.PartialMixin[source]¶
Bases:
object- property args¶
- backend = ''¶
- property kwargs¶
- classmethod load(token: str) → PartialMixin | None[source]¶
- property request_data: Mapping[str, Any] | None¶
Effective data for a resume, including legacy partial snapshots.
- classmethod store(partial: PartialMixin) → PartialMixin[source]¶
- token = ''¶
- class social_core.storage.PipelineUserProtocol(*args, **kwargs)[source]¶
Bases:
UserProtocol,Protocol
- class social_core.storage.UserMixin[source]¶
Bases:
object- ACCESS_TOKEN_EXPIRED_THRESHOLD = 5¶
- 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
- 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
- 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_username(user: UserProtocol) → str[source]¶
Return the username for given user
- 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.
- 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
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:
AuthExceptionA 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:
AuthExceptionAuthorization 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:
SocialAuthBaseExceptionThe 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:
AuthExceptionCredentials 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:
SocialAuthBaseExceptionBroad 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:
AuthExceptionThe 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:
AuthExceptionA 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:
AuthExceptionA 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:
AuthExceptionA 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:
AuthExceptionAuthentication 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:
AuthExceptionThe 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:
ValueErrorBroad catch boundary for social-auth failures, including configuration.
- default_code = 'unknown_error'¶
- class social_core.utils.PartialPipelineResult(partial: 'PartialMixin | None' = None, response: 'HttpResponseProtocol | None' = None, halt: 'bool' = False)[source]¶
-
- 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]¶
- 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, ormethod.invalidate(instance, *args, **kwargs)to clear one entry. Callmethod.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.
- 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.first(func, items)[source]¶
Return the first item in the list for what func returns True
- 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
valueuses a non-web scheme that has been explicitly allowed.URI construction helpers such as
build_absolute_urionly 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.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_schemesdefaults 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 theALLOWED_REDIRECT_SCHEMESsetting.
- 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.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_is_active(user: UserProtocol | None) → bool[source]¶
- social_core.utils.user_is_authenticated(user: UserProtocol | None) → bool[source]¶