Social Login in Django: Library or Manual? [Complete Guide + Lab]

Want your users to log in with Google, Facebook, or GitHub accounts without creating a new password? This guide walks you through two complete ways to implement Social Login in Django — using django-allauth and building OAuth2 manually from scratch.


Why Use Social Login?

Social Login allows users to authenticate via trusted platforms like Google, Facebook, GitHub, etc., without creating a new account.

Benefits:

  • Faster login: Just one click to authenticate
  • Secure: Authentication handled by big providers
  • Better UX: Less friction for users
  • Reduced security liability: No password management on your side

Source Code for Solution 2:

https://gitlab.com/cuong-labs/django_social_login


How OAuth2 Works (Simplified Flow)

Social Login typically uses the OAuth2 Authorization Code Flow:

[User clicks “Login with Google”]
        ↓
[Django redirects to Google]
        ↓
[User logs in + grants permission]
        ↓
[Google sends back an authorization code]
        ↓
[Django exchanges code for access_token]
        ↓
[Django uses token to fetch user info]
        ↓
[User is created or linked → logged in]

Solution 1: Use django-allauth (Simple & Fast)

This is the recommended approach if you want to integrate social login quickly and securely.

Step-by-step Integration

Step 1: Install the Library

pip install django-allauth

Step 2: Configure settings.py

INSTALLED_APPS = [
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',
]

SITE_ID = 1

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    'allauth.account.auth_backends.AuthenticationBackend',
)

LOGIN_REDIRECT_URL = '/'

Step 3: Register OAuth Client on Google

  1. Go to Google Cloud Console
  2. Create a project → Enable OAuth Consent Screen
  3. Create OAuth Client ID
    - Redirect URI: http://localhost:8000/accounts/google/login/callback/

Step 4: Add your Google credentials

SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'APP': {
            'client_id': 'YOUR_CLIENT_ID',
            'secret': 'YOUR_CLIENT_SECRET',
        },
        'SCOPE': ['profile', 'email']
    }
}

Step 5: Setup URLs

from django.urls import path, include

urlpatterns = [
    path('accounts/', include('allauth.urls')),
]

Step 6: Run and Test

python manage.py migrate
python manage.py createsuperuser
python manage.py runserver

Visit /accounts/login/ → Click “Login with Google” → You’re authenticated!


Solution 2: Manual OAuth2 Flow (Full Control)

You might prefer to build the flow manually if:

  • You want full control over authentication steps
  • You’re creating a backend-only API (no sessions)
  • You need a deeper understanding of OAuth2

How to Build Your Own Social Login Flow

<a href="/oauth2/login/">Login with Google</a>

2. Redirect to Google

from django.shortcuts import redirect
from urllib.parse import urlencode

def oauth2_login(request):
    params = {
        'client_id': GOOGLE_CLIENT_ID,
        'redirect_uri': GOOGLE_REDIRECT_URI,
        'response_type': 'code',
        'scope': 'email profile',
        'access_type': 'online',
    }
    url = f"https://accounts.google.com/o/oauth2/auth?{urlencode(params)}"
    return redirect(url)

3. Handle Google callback

import requests
from django.contrib.auth import login
from django.contrib.auth.models import User
from django.http import JsonResponse, HttpResponseBadRequest

def oauth2_callback(request):
    code = request.GET.get('code')
    if not code:
        return HttpResponseBadRequest("Missing code")

    # Exchange code for token
    token_response = requests.post('https://oauth2.googleapis.com/token', data={
        'code': code,
        'client_id': GOOGLE_CLIENT_ID,
        'client_secret': GOOGLE_CLIENT_SECRET,
        'redirect_uri': GOOGLE_REDIRECT_URI,
        'grant_type': 'authorization_code'
    }).json()

    access_token = token_response.get('access_token')

    # Get user info from Google
    user_info = requests.get('https://www.googleapis.com/oauth2/v1/userinfo',
        headers={'Authorization': f'Bearer {access_token}'}).json()

    email = user_info['email']
    name = user_info['name']

    user, _ = User.objects.get_or_create(username=email, defaults={'first_name': name, 'email': email})
    login(request, user)

    return JsonResponse({'message': 'Logged in', 'user': user.email})

🔐 You can replace Django sessions with JWT tokens for SPA/mobile apps.


Which Approach Should You Use?

Criteria django-allauth Manual OAuth2
Quick setup ✅ Fast & ready-to-use ❌ Slower
Custom control 🔸 Limited ✅ Full control
Backend API (JWT) ✅ Possible with tweaks ✅ Ideal
Advanced customization 🔸 Requires adapter override ✅ Free-form logic
For learning ❌ Less educational ✅ Teaches OAuth2 deeply

Best Practices for Social Login

  • Never hardcode secrets – use environment variables or vaults
  • Always register the correct redirect URI
  • Ask for minimal OAuth scopes (email, profile only)
  • Test edge cases: permission denial, expired tokens, duplicate emails
  • Use HTTPS in production & secure your session or JWT cookies

Conclusion

Social Login helps your app:

  • Improve user experience
  • Reduce password-related risks
  • Leverage existing user identities from Google or others

Choose the method that fits your project:

  • Use django-allauth for quick setup and multiple providers
  • Go manual for APIs, full control, or deeper learning

💬 Bình luận