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

EXTRA_DATA: list[str | tuple[str, str] | tuple[str, str, bool]] | None = None
GET_ALL_EXTRA_DATA = False
ID_KEY: str = ''
REQUIRES_EMAIL_VALIDATION = False
SEND_USER_AGENT = True
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_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_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) 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_querystring(url, *args, **kwargs) dict[str, str][source]
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_id(details, response)[source]

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

get_user_names(fullname='', first_name='', last_name='')[source]
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]
process_error(data) 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) Response[source]
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
uses_redirect() bool[source]

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

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 = ''
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')[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) 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

process_error(data) 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) 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 = ''
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

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 user unique id provided by service

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) 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

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
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'
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

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) str[source]
get_user_id(details, response)[source]

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

id_token_issuer() str[source]
jwks_uri() str[source]
name = 'oidc'
oidc_config(*args, **kwargs)
oidc_endpoint() str[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) dict[Any, Any][source]

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

revoke_token_url(token, uid) str[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

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_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_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, **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_uid(backend: BaseAuth, details, response, *args, **kwargs)[source]
social_core.pipeline.social_auth.social_user(backend: BaseAuth, uid, user: UserProtocol | None = None, *args, **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.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_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_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]
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)[source]

Return current request data (POST or GET)

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]
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 = ''
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]
classmethod make_code(email: str) CodeMixin[source]
abstractmethod save()[source]
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
classmethod prepare(backend: str, next_step: int, data: dict[str, Any]) PartialMixin[source]
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)[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)[source]

Return UserSocialAuth for given provider and uid

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

provider = ''
refresh_token(strategy: BaseStrategy, *args, **kwargs) None[source]
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

exception social_core.exceptions.AuthAlreadyAssociated(backend: BaseAuth, *args, **kwargs)[source]

Bases: AuthException

A different user has already associated the target social account

exception social_core.exceptions.AuthCanceled(*args, **kwargs)[source]

Bases: AuthException

Auth process was canceled by user.

exception social_core.exceptions.AuthConnectionError(backend: BaseAuth, *args, **kwargs)[source]

Bases: AuthException

Connection error duing authentication.

exception social_core.exceptions.AuthException(backend: BaseAuth, *args, **kwargs)[source]

Bases: SocialAuthBaseException

Auth process exception.

exception social_core.exceptions.AuthFailed(backend: BaseAuth, *args, **kwargs)[source]

Bases: AuthException

Auth process failed for some reason.

exception social_core.exceptions.AuthForbidden(backend: BaseAuth, *args, **kwargs)[source]

Bases: AuthException

Authentication for this user is forbidden

exception social_core.exceptions.AuthInvalidParameter(backend: BaseAuth, parameter: str, *args, **kwargs)[source]

Bases: AuthMissingParameter

Invalid value for parameter to start or complete the process.

exception social_core.exceptions.AuthMissingParameter(backend: BaseAuth, parameter: str, *args, **kwargs)[source]

Bases: AuthException

Missing parameter needed to start or complete the process.

exception social_core.exceptions.AuthNotImplementedParameter(backend: BaseAuth, parameter: str, *args, **kwargs)[source]

Bases: AuthMissingParameter

Optional parameter not implemented to start or complete the process.

exception social_core.exceptions.AuthStateForbidden(backend: BaseAuth, *args, **kwargs)[source]

Bases: AuthException

State parameter is incorrect.

exception social_core.exceptions.AuthStateMissing(backend: BaseAuth, *args, **kwargs)[source]

Bases: AuthException

State parameter is incorrect.

exception social_core.exceptions.AuthTokenError(backend: BaseAuth, *args, **kwargs)[source]

Bases: AuthException

Auth token error.

exception social_core.exceptions.AuthTokenRevoked(backend: BaseAuth, *args, **kwargs)[source]

Bases: AuthException

User revoked the access_token in the provider.

exception social_core.exceptions.AuthUnknownError(backend: BaseAuth, *args, **kwargs)[source]

Bases: AuthException

Unknown auth process error.

exception social_core.exceptions.AuthUnreachableProvider(backend: BaseAuth, *args, **kwargs)[source]

Bases: AuthException

Cannot reach the provider

exception social_core.exceptions.DefaultStrategyMissingError[source]

Bases: SocialAuthBaseException

Default strategy is not configured.

exception social_core.exceptions.InvalidEmail(backend: BaseAuth, *args, **kwargs)[source]

Bases: AuthException

exception social_core.exceptions.InvalidExpiryValue(field_name: str, value: object)[source]

Bases: SocialAuthBaseException

Invalid expiry value in extra_data.

exception social_core.exceptions.MissingBackend(backend_name: str)[source]

Bases: WrongBackend

exception social_core.exceptions.NotAllowedToDisconnect[source]

Bases: SocialAuthBaseException

User is not allowed to disconnect it’s social account.

exception social_core.exceptions.SocialAuthBaseException[source]

Bases: ValueError

Base class for pipeline exceptions.

exception social_core.exceptions.SocialAuthImproperlyConfiguredError[source]

Bases: SocialAuthBaseException

Raised when configuration is invalid.

exception social_core.exceptions.StrategyMissingBackendError[source]

Bases: SocialAuthBaseException

Strategy storage backend is not configured.

exception social_core.exceptions.StrategyMissingFeatureError(strategy_name: str, feature_name: str)[source]

Bases: SocialAuthBaseException

Strategy does not support this.

exception social_core.exceptions.WrongBackend(backend_name: str)[source]

Bases: SocialAuthBaseException

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.

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_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]
social_core.utils.is_url(value: str | None) bool[source]
social_core.utils.module_member(name)[source]
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, **kwargs) PartialPipelineResult[source]
social_core.utils.sanitize_redirect(hosts: list[str], redirect_to: str | Any) 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.

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)[source]