OAuth with Google#
Installation#
pip install django-allauth
Setup#
# settings.py
INSTALLED_APPS = [
# ...
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
]
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
]
SITE_ID = 1
# Allauth settings
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'
URLs#
# urls.py
from django.urls import path, include
urlpatterns = [
# ...
path('accounts/', include('allauth.urls')),
]
Google OAuth Setup#
1. Google Cloud Console#
- Go to Google Cloud Console
- Create project or select existing
- Enable Google+ API
- Go to Credentials → Create Credentials → OAuth 2.0 Client ID
- Configure consent screen
- Add authorized redirect URI:
http://localhost:8000/accounts/google/login/callback/ - Copy Client ID and Client Secret
2. Django Settings#
# settings.py
SOCIALACCOUNT_PROVIDERS = {
'google': {
'SCOPE': [
'profile',
'email',
],
'AUTH_PARAMS': {
'access_type': 'online',
},
'APP': {
'client_id': config('GOOGLE_CLIENT_ID'),
'secret': config('GOOGLE_CLIENT_SECRET'),
'key': ''
}
}
}
# .env
GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=your-client-secret
3. Admin Configuration#
# In Django admin, go to:
# Social Applications → Add
# Provider: Google
# Name: Google
# Client id: (from Google Console)
# Secret key: (from Google Console)
# Sites: Select your site
Usage#
Login Template#
<!-- templates/account/login.html -->
<h1>Login</h1>
<!-- Regular login -->
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
<!-- Google OAuth -->
<a href="{% url 'google_login' %}">Login with Google</a>
Signup Template#
<!-- templates/account/signup.html -->
<h1>Sign Up</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Sign Up</button>
</form>
<a href="{% url 'google_login' %}">Sign up with Google</a>
Custom User Model#
# models.py
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
email = models.EmailField(unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
# settings.py
AUTH_USER_MODEL = 'myapp.User'
Customize OAuth Flow#
# settings.py
SOCIALACCOUNT_ADAPTER = 'myapp.adapters.CustomSocialAccountAdapter'
# adapters.py
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
class CustomSocialAccountAdapter(DefaultSocialAccountAdapter):
def pre_social_login(self, request, sociallogin):
# Custom logic before login
pass
def populate_user(self, request, sociallogin, data):
user = super().populate_user(request, sociallogin, data)
# Custom user population
return user
Access User Info#
# views.py
def profile(request):
user = request.user
# Access Google profile
social_account = user.socialaccount_set.filter(provider='google').first()
if social_account:
extra_data = social_account.extra_data
google_id = extra_data.get('id')
picture = extra_data.get('picture')
return render(request, 'profile.html', {'user': user})
Production Settings#
# settings.py
# Update redirect URI in Google Console
# http://yourdomain.com/accounts/google/login/callback/
SOCIALACCOUNT_PROVIDERS = {
'google': {
'APP': {
'client_id': config('GOOGLE_CLIENT_ID'),
'secret': config('GOOGLE_CLIENT_SECRET'),
}
}
}
Next: Django Channels