Social Authentication¶
Integrate OAuth providers like Google, GitHub, and Facebook using django-allauth.
Maintainer's Note
dj-rest-auth has optional and narrow support for django-allauth social authentication. The focus is on providing a clean API wrapper for the most common use cases.
Overview¶
sequenceDiagram
participant User
participant SPA as Your App
participant API as dj-rest-auth
participant Provider as OAuth Provider
User->>SPA: Click "Login with Google"
SPA->>Provider: Redirect to OAuth consent
Provider->>User: Show consent screen
User->>Provider: Grant permission
Provider->>SPA: Redirect with code
SPA->>API: POST /auth/google/ {code}
API->>Provider: Exchange code for tokens
Provider-->>API: Access token + user info
API->>API: Create/get user account
API-->>SPA: Auth token/JWT
Setup¶
1. Install Dependencies¶
This installs django-allauth.
2. Configure Django Settings¶
INSTALLED_APPS = [
# Django
'django.contrib.sites',
# ...
# REST Framework
'rest_framework',
'rest_framework.authtoken',
# Allauth
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google', # Add providers you need
'allauth.socialaccount.providers.github',
'allauth.socialaccount.providers.facebook',
# dj-rest-auth
'dj_rest_auth',
'dj_rest_auth.registration',
]
MIDDLEWARE = [
# ...
'allauth.account.middleware.AccountMiddleware',
]
SITE_ID = 1
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
]
3. Run Migrations¶
Google OAuth¶
1. Create Google OAuth Credentials¶
- Go to Google Cloud Console
- Create a new project or select existing
- Navigate to APIs & Services → Credentials
- Click Create Credentials → OAuth 2.0 Client IDs
- Configure consent screen if prompted
- Select Web application
- Add authorized redirect URIs:
- Development:
http://localhost:3000/auth/google/callback - Production:
https://yourapp.com/auth/google/callback - Save your Client ID and Client Secret
2. Add Social Application in Django Admin¶
- Go to
/admin/ - Navigate to Social Applications
- Click Add
- Fill in:
- Provider: Google
- Name: Google
- Client ID: Your client ID
- Secret key: Your client secret
- Sites: Select your site
3. Create the View¶
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from dj_rest_auth.registration.views import SocialLoginView
class GoogleLogin(SocialLoginView):
adapter_class = GoogleOAuth2Adapter
callback_url = 'http://localhost:3000/auth/google/callback'
client_class = OAuth2Client
4. Add URL¶
from django.urls import path
from .views import GoogleLogin
urlpatterns = [
# ...
path('api/auth/google/', GoogleLogin.as_view(), name='google_login'),
]
5. Frontend Flow¶
const GOOGLE_CLIENT_ID = 'your-client-id';
const REDIRECT_URI = 'http://localhost:3000/auth/google/callback';
function GoogleLoginButton() {
const handleLogin = () => {
const authUrl = new URL('https://accounts.google.com/o/oauth2/v2/auth');
authUrl.searchParams.set('client_id', GOOGLE_CLIENT_ID);
authUrl.searchParams.set('redirect_uri', REDIRECT_URI);
authUrl.searchParams.set('response_type', 'code');
authUrl.searchParams.set('scope', 'openid email profile');
authUrl.searchParams.set('access_type', 'offline');
authUrl.searchParams.set('prompt', 'consent');
window.location.href = authUrl.toString();
};
return <button onClick={handleLogin}>Login with Google</button>;
}
// Callback page component
async function handleGoogleCallback() {
const params = new URLSearchParams(window.location.search);
const code = params.get('code');
const response = await fetch('/api/auth/google/', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code }),
});
const data = await response.json();
// Handle successful login
}
function GoogleLoginButton() {
useEffect(() => {
google.accounts.id.initialize({
client_id: 'your-client-id',
callback: handleCredentialResponse,
});
google.accounts.id.renderButton(
document.getElementById('google-button'),
{ theme: 'outline', size: 'large' }
);
}, []);
async function handleCredentialResponse(response: any) {
// response.credential is the ID token
const res = await fetch('/api/auth/google/', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id_token: response.credential }),
});
// Handle response
}
return <div id="google-button"></div>;
}
GitHub OAuth¶
1. Create GitHub OAuth App¶
- Go to GitHub Developer Settings
- Click New OAuth App
- Fill in:
- Application name: Your app name
- Homepage URL:
http://localhost:3000 - Authorization callback URL:
http://localhost:3000/auth/github/callback - Save Client ID and Client Secret
2. Add Social Application¶
Add via Django Admin (similar to Google setup).
3. Create the View¶
from allauth.socialaccount.providers.github.views import GitHubOAuth2Adapter
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from dj_rest_auth.registration.views import SocialLoginView
class GitHubLogin(SocialLoginView):
adapter_class = GitHubOAuth2Adapter
callback_url = 'http://localhost:3000/auth/github/callback'
client_class = OAuth2Client
4. Add URL¶
from .views import GitHubLogin
urlpatterns = [
# ...
path('api/auth/github/', GitHubLogin.as_view(), name='github_login'),
]
5. Frontend Flow¶
const GITHUB_CLIENT_ID = 'your-client-id';
const REDIRECT_URI = 'http://localhost:3000/auth/github/callback';
function GitHubLoginButton() {
const handleLogin = () => {
const authUrl = new URL('https://github.com/login/oauth/authorize');
authUrl.searchParams.set('client_id', GITHUB_CLIENT_ID);
authUrl.searchParams.set('redirect_uri', REDIRECT_URI);
authUrl.searchParams.set('scope', 'read:user user:email');
window.location.href = authUrl.toString();
};
return <button onClick={handleLogin}>Login with GitHub</button>;
}
// Callback handler
async function handleGitHubCallback() {
const code = new URLSearchParams(window.location.search).get('code');
const response = await fetch('/api/auth/github/', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code }),
});
const data = await response.json();
// Handle successful login
}
Facebook OAuth¶
1. Create Facebook App¶
- Go to Facebook Developers
- Create a new app
- Add Facebook Login product
- Configure Valid OAuth Redirect URIs
2. Create the View¶
from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter
from dj_rest_auth.registration.views import SocialLoginView
class FacebookLogin(SocialLoginView):
adapter_class = FacebookOAuth2Adapter
3. Add URL¶
from .views import FacebookLogin
urlpatterns = [
# ...
path('api/auth/facebook/', FacebookLogin.as_view(), name='facebook_login'),
]
Connecting Social Accounts¶
Allow users to connect additional social accounts to their existing account:
1. Create Connect Views¶
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from allauth.socialaccount.providers.github.views import GitHubOAuth2Adapter
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from dj_rest_auth.registration.views import SocialConnectView
class GoogleConnect(SocialConnectView):
adapter_class = GoogleOAuth2Adapter
callback_url = 'http://localhost:3000/auth/google/callback'
client_class = OAuth2Client
class GitHubConnect(SocialConnectView):
adapter_class = GitHubOAuth2Adapter
callback_url = 'http://localhost:3000/auth/github/callback'
client_class = OAuth2Client
2. Add URLs¶
from .views import GoogleConnect, GitHubConnect
urlpatterns = [
# ...
path('api/auth/google/connect/', GoogleConnect.as_view(), name='google_connect'),
path('api/auth/github/connect/', GitHubConnect.as_view(), name='github_connect'),
]
Authentication Required
Connect views require the user to be authenticated. The social account will be linked to the current user.
Managing Social Accounts¶
List Connected Accounts¶
from dj_rest_auth.registration.views import SocialAccountListView
urlpatterns = [
# ...
path('api/auth/social-accounts/', SocialAccountListView.as_view(), name='social_accounts'),
]
Response:
[
{
"id": 1,
"provider": "google",
"uid": "123456789",
"last_login": "2026-02-15T10:30:00Z",
"date_joined": "2026-01-01T09:00:00Z"
},
{
"id": 2,
"provider": "github",
"uid": "987654321",
"last_login": "2026-02-14T15:45:00Z",
"date_joined": "2026-02-01T12:00:00Z"
}
]
Disconnect Social Account¶
from dj_rest_auth.registration.views import SocialAccountDisconnectView
urlpatterns = [
# ...
path(
'api/auth/social-accounts/<int:pk>/disconnect/',
SocialAccountDisconnectView.as_view(),
name='social_account_disconnect'
),
]
curl -X POST http://localhost:8000/api/auth/social-accounts/1/disconnect/ \
-H "Authorization: Token your-token"
JWT with Social Auth¶
Social authentication works seamlessly with JWT:
REST_AUTH = {
'USE_JWT': True,
'JWT_AUTH_COOKIE': 'access',
'JWT_AUTH_REFRESH_COOKIE': 'refresh',
}
The social login endpoints will return JWT tokens (or set cookies) just like regular login.
Troubleshooting¶
"Callback URL Mismatch"¶
Ensure the callback URL in your view matches exactly: - The URL registered with the OAuth provider - The URL your frontend redirects to
"Access Denied" or "Invalid Grant"¶
- Check that you're using the correct flow (code vs token)
- Verify client ID and secret are correct
- Ensure the authorization code hasn't expired (use immediately)
"User Already Exists"¶
If a user tries to login with a social account that's linked to a different email:
Or handle it in your frontend by prompting the user to connect accounts.