Social Authentication Providers

OAuth 2.0 social login integration guide for Google, GitHub, LinkedIn, and Facebook

Social Authentication Providers

OAuth 2.0 social login integration via django-allauth socialaccount.

Configured Providers

Google

SOCIALACCOUNT_PROVIDERS = {
    "google": {
        "SCOPE": ["profile", "email"],
        "AUTH_PARAMS": {"access_type": "online"},
    },
}

Required Environment Variables:

GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=your-client-secret

Google Cloud Console Configuration

Navigate to: Google Cloud Console → APIs & Services → Credentials → OAuth 2.0 Client IDs

Authorized JavaScript Origins:

EnvironmentOrigin
Local devhttp://localhost:8080
Productionhttps://your-backend-domain.com

Authorized Redirect URIs:

EnvironmentRedirect URI
Local devhttp://localhost:8080/accounts/google/login/callback/
Productionhttps://your-backend-domain.com/accounts/google/login/callback/

Note: The callback URL points to the Django backend (port 8080), not the Next.js frontend (port 3000). Django handles the OAuth callback, sets the session cookie, then redirects to the frontend.

GitHub

SOCIALACCOUNT_PROVIDERS = {
    "github": {
        "SCOPE": ["user", "repo", "read:org"],
    },
}

Required Environment Variables:

GITHUB_CLIENT_ID=your-client-id
GITHUB_CLIENT_SECRET=your-client-secret

Callback URL (configure in GitHub OAuth App):

https://your-domain.com/accounts/github/login/callback/

LinkedIn

SOCIALACCOUNT_PROVIDERS = {
    "linkedin": {
        "SCOPE": ["r_basicprofile", "r_emailaddress"],
        "PROFILE_FIELDS": [
            "id",
            "first-name",
            "last-name",
            "email-address",
            "picture-url",
            "public-profile-url",
        ],
    },
}

Required Environment Variables:

LINKEDIN_CLIENT_ID=your-client-id
LINKEDIN_CLIENT_SECRET=your-client-secret

Facebook

SOCIALACCOUNT_PROVIDERS = {
    "facebook": {
        "METHOD": "oauth2",
        "SCOPE": ["email", "public_profile"],
        "AUTH_PARAMS": {"auth_type": "reauthenticate"},
        "INIT_PARAMS": {"cookie": True},
        "FIELDS": ["id", "first_name", "last_name", "name", "picture"],
        "EXCHANGE_TOKEN": True,
        "VERSION": "v7.0",
    },
}

Required Environment Variables:

FACEBOOK_APP_ID=your-app-id
FACEBOOK_APP_SECRET=your-app-secret

OAuth Redirect Flow

┌──────────────────┐      ┌─────────────────┐      ┌──────────────┐
│   Next.js App    │      │  Django Backend │      │    Google    │
│   (port 3000)    │      │   (port 8080)   │      │              │
└────────┬─────────┘      └────────┬────────┘      └──────┬───────┘
         │                         │                      │
         │ 1. socialLogin('google', '/projects')          │
         │ ─────────────────────────▶                     │
         │   window.location.href =                       │
         │   /accounts/google/login/?next=/projects       │
         │                         │                      │
         │                         │ 2. Redirect to OAuth │
         │                         │ ─────────────────────▶
         │                         │                      │
         │                         │ 3. User authenticates│
         │                         │ ◀─────────────────────
         │                         │                      │
         │   4. Callback to        │                      │
         │   /accounts/google/login/callback/             │
         │                         │                      │
         │ 5. Redirect to          │                      │
         │ {FRONTEND_URL}/projects │                      │
         │ ◀───────────────────────                       │
         │ (with session cookie)   │                      │
  1. Frontend calls socialLogin('google', callbackUrl) which redirects to Django
  2. Django redirects to Google OAuth consent screen
  3. User authenticates with Google
  4. Google redirects back to Django callback URL
  5. Django creates session, sets cookie, redirects to FRONTEND_URL

URL Configuration

Social auth URLs are registered at /accounts/:

# config/urls.py
urlpatterns = [
    path("accounts/", include("allauth.urls")),
]

Provider URL Patterns

# apps/accounts/socialaccount_urls.py
provider_urlpatterns = [
    path("google/login/", google_oauth2_login, name="login"),
    path("google/login/callback/", google_oauth2_callback, name="google_callback"),
    path("github/login/", github_login, name="github_login"),
    path("github/login/callback/", github_login_callback, name="github_callback"),
    # ... other providers
]

Frontend Integration

Initiating Social Login

// hooks/use-auth.ts
socialLogin: (provider: string, callbackUrl: string) => {
  const baseUrl = process.env.NEXT_PUBLIC_API_URL;
  window.location.href = `${baseUrl}/accounts/${provider}/login/?next=${encodeURIComponent(callbackUrl)}`;
}

Login Page Implementation

// app/(auth)/login/page.tsx
const { socialLogin, config } = useAuth();
const enabledProviders = config?.socialaccount?.providers ?? [];

{enabledProviders.map((provider) => (
  <Button
    key={provider.id}
    onClick={() => socialLogin(provider.id, `${origin}/projects`)}
  >
    Login with {provider.name}
  </Button>
))}

Custom Social Adapter

The SocialAccountAdapter handles post-login redirects:

# apps/accounts/adapters.py
class SocialAccountAdapter(DefaultSocialAccountAdapter):
    def is_open_for_signup(self, request, sociallogin):
        return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True)

    def get_connect_redirect_url(self, request, socialaccount):
        return f"{settings.FRONTEND_URL}/settings?tab=connected-accounts"

    def get_login_redirect_url(self, request):
        next_url = request.GET.get("next") or request.session.get("next")
        if next_url and next_url.startswith(settings.FRONTEND_URL):
            return next_url
        return f"{settings.FRONTEND_URL}/projects"

Configuration Settings

# Allow social login via GET (for redirect flow)
SOCIALACCOUNT_LOGIN_ON_GET = True

# Use custom adapter
SOCIALACCOUNT_ADAPTER = "apps.accounts.adapters.SocialAccountAdapter"

Database Setup

Social apps are configured via Django admin or migrations:

from allauth.socialaccount.models import SocialApp
from django.contrib.sites.models import Site

# Create social app
app = SocialApp.objects.create(
    provider='google',
    name='Google',
    client_id=settings.GOOGLE_CLIENT_ID,
    secret=settings.GOOGLE_CLIENT_SECRET,
)

# Associate with site
site = Site.objects.get_current()
app.sites.add(site)

Handling Errors

Error callbacks redirect to the frontend:

# apps/accounts/views.py
@require_GET
def socialaccount_login_error(request):
    return redirect(f"{FRONTEND_URL}/auth/error?type=social_login")

@require_GET
def socialaccount_login_cancelled(request):
    return redirect(f"{FRONTEND_URL}/auth/login?message=cancelled")

Connecting Additional Accounts

Users can connect multiple social accounts to their profile:

GET /accounts/google/login/?process=connect

Redirect after connection:

/settings?tab=connected-accounts

Setup Checklist

Google OAuth Setup

  1. Create OAuth 2.0 Client ID in Google Cloud Console
  2. Set GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET env vars
  3. Configure Authorized JavaScript Origins (backend URL)
  4. Configure Authorized Redirect URI (/accounts/google/login/callback/)
  5. Create SocialApp record in database (via admin or shell)
  6. Set FRONTEND_URL env var to Next.js app URL
  7. Test with socialLogin('google', callbackUrl) from frontend

GitHub OAuth Setup

  1. Create OAuth App in GitHub Developer Settings
  2. Set GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET env vars
  3. Set Authorization callback URL to /accounts/github/login/callback/
  4. Create SocialApp record in database
  5. Test with socialLogin('github', callbackUrl) from frontend

Troubleshooting

Common Issues

  1. Callback URL mismatch: Ensure the callback URL in provider console matches exactly
  2. Scope errors: Some scopes require app verification (e.g., Google sensitive scopes)
  3. HTTPS required: Most providers require HTTPS for production callbacks
  4. CORS errors: Social login uses redirects, not AJAX — CORS doesn't apply

Debug Mode

# Enable detailed logging
LOGGING = {
    'loggers': {
        'allauth': {
            'level': 'DEBUG',
        },
    },
}

Last updated on

On this page