Django Social Auth

5.7.0 · active · verified Thu Apr 09

social-auth-app-django is the official Django component of the Python Social Auth ecosystem, providing an easy-to-set-up social authentication and registration mechanism for Django projects. It integrates `social-auth-core` to support a wide array of OAuth and OpenID providers. The library is actively maintained, with version 5.7.0 being the latest, and focuses on supporting current Django releases.

Warnings

Install

Imports

Quickstart

This quickstart outlines the essential configuration for integrating Google OAuth2 login into a Django project. It covers adding `social_django` to `INSTALLED_APPS` and `MIDDLEWARE`, configuring authentication backends, defining OAuth2 credentials using environment variables, setting redirect URLs, adding context processors for templates, and including the `social_django` URLs. Remember to run `python manage.py migrate` after configuration.

import os

# settings.py
INSTALLED_APPS = [
    # ... existing apps ...
    'django.contrib.auth',
    'django.contrib.sessions',
    'social_django',
]

MIDDLEWARE = [
    # ... existing middleware ...
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'social_django.middleware.SocialAuthExceptionMiddleware',
]

AUTHENTICATION_BACKENDS = (
    'social_core.backends.google.GoogleOAuth2',
    'django.contrib.auth.backends.ModelBackend',
)

SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = os.environ.get('GOOGLE_OAUTH2_KEY', '')
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = os.environ.get('GOOGLE_OAUTH2_SECRET', '')
SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ['email', 'profile']

LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                # ... existing context processors ...
                'social_django.context_processors.backends',
                'social_django.context_processors.login_redirect',
            ],
        },
    },
]

# urls.py
from django.urls import include, path

urlpatterns = [
    path('oauth/', include('social_django.urls', namespace='social')),
    # ... other paths ...
]

# In your login template (e.g., login.html)
# <a href="{% url 'social:begin' 'google-oauth2' %}">Login with Google</a>

view raw JSON →