Introduction
In today’s digital landscape, user convenience and engagement are paramount for the success of any web application. One powerful tool that can significantly enhance both of these aspects is social login. Imagine allowing your users to seamlessly sign in to your Django-powered website using their existing social media accounts such as Facebook, Google, or Apple. This not only simplifies the registration process but also eliminates the need for users to remember yet another set of credentials.
In this blog post, we’ll explore how to implement social login functionality in a Django project using the Django-Allauth package. Django-Allauth is a comprehensive authentication solution for Django that provides support for social login straight out of the box. We’ll walk through the setup process, customization options, handling user data, testing, and security considerations to ensure a smooth and secure integration of social login into your Django application.
Whether you’re building a new Django project or looking to enhance an existing one, incorporating social login can greatly improve the user experience and drive user engagement. So, let’s dive in and empower our Django applications with the power of social login!
Step 1: Setting Up Project Workflow
Initially, set up a new virtual environment, followed by creating a Django project and a Django App within it.
1.1 Create a virtual environment.
python3 -m venv env_social_login
1.2 Active virtual environment in Linux.
source env_social_login/bin/activate
1.3 To activate a virtual environment in Windows, run the below command.
env_social_login\Script\activate
1.4 Install Django within your virtual environment to encapsulate its dependencies and version, ensuring compatibility with your project.
pip install django
1.5 Create a new Django project using the following command.
django-admin startproject social_login
cd social_login/
1.6 Create a new App using the following command.
python manage.py startapp authapp
Step 2: Installing Requirements
Install the all-auth package within your Django project’s virtual environment, and configure its settings as necessary to meet requirements.
2.1 Install the all-auth package within your virtual environment by executing the following installation command.
pip install django-allauth
pip install django-allauth[socialaccount]
2.2 Configure the settings for all-auth according to your project’s requirements, ensuring proper integration and functionality within your Django application.
- Include the following configuration settings within the
settings.py
file of your social_login project:
- Include the following configuration settings within the
import os
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.request',
],
},
},
]
AUTHENTICATION_BACKENDS = [
# Needed to login by username in Django admin, regardless of `allauth`
'django.contrib.auth.backends.ModelBackend',
# `allauth` specific authentication methods, such as login by email
'allauth.account.auth_backends.AuthenticationBackend',
]
- Add the following entry to the
INSTALLED_APPS
list within thesettings.py
file of your project:
- Add the following entry to the
'authapp',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google', # for google login
-
- Add the following middleware configuration to the
MIDDLEWARE
list within thesettings.py
file of your project:
- Add the following middleware configuration to the
'allauth.account.middleware.AccountMiddleware',
- Add the following code snippet to the
urls.py
file of your project:
- Add the following code snippet to the
from django.urls import path, include
path('accounts/', include('allauth.urls')),
-
- Execute the following command to generate your database tables, create a superuser account, and gain access to the admin panel:
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver
Now you can access the admin panel using the below link.
Step 3: Setting Up the Google Cloud Platform Project
To set up the Google Cloud Platform (GCP) project and enable API for login using Google accounts, follow these steps:
3.1 Create a Google Cloud Platform Project:
- Go to the Google Cloud Console.
- Click on “Select a project” and then click on “New Project”.
- Follow the prompts to create your new project, giving it an appropriate name.
3.2 Enable Google API for Authentication:
- In the Google Cloud Console, navigate to the “APIs & Services” > “Library” section.
- Search for Google+ and select Google+ API.
- Click on “Enable” to activate the API.
- Search for People API and select Google People API.
- Click on “Enable” to activate the API.
3.3 Set Up OAuth Consent Screen:
- In the Google Cloud Console, navigate to “APIs & Services” > “OAuth consent screen”.
- Choose “External” or “Internal” based on your use case and follow the prompts to configure the consent screen details such as the application name, user support email, etc.
- Save the consent screen configuration.
3.4 Create OAuth 2.0 Credentials:
- In the Google Cloud Console, navigate to “APIs & Services” > “Credentials”.
- Click on “Create Credentials” and select “OAuth client ID”.
- Choose the application type Web application and configure the authorized redirect following URIs.
- http://127.0.0.1:8000/accounts/google/login/callback/
- http://localhost:8000/accounts/google/login/callback/
- https://<domain_name>/accounts/google/login/callback/
- After creating the OAuth client ID, you will receive a client ID and client secret.
Step 4: Configuring Client ID and Client Secret in Django
4.1 Include the following configuration in your settings.py
file:
SOCIALACCOUNT_PROVIDERS = {
'google': {
'APP': {
'client_id' : ,
'secret' :
},
'SCOPE': [
'profile',
'email',
],
'AUTH_PARAMS': {
'access_type': 'online',
},
'OAUTH_PKCE_ENABLED': True,
}
}
LOGIN_URL = 'login'
LOGOUT_URL = 'logout'
LOGIN_REDIRECT_URL = 'dashboard'
LOGOUT_REDIRECT_URL = 'login'
SOCIALACCOUNT_AUTO_SIGNUP = True
SOCIALACCOUNT_LOGIN_ON_GET = True
4.2 Add the following code snippet to the views.py
file of your Django app:
from django.shortcuts import render, redirect
# Create your views here.
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout
# Create your views here.
def userLogin(request):
return render(request,'login.html')
@login_required
def dashboard(request):
print(request)
return render(request,'dashboard.html')
def userlogout(request):
# Logout the user
logout(request)
return redirect('login')
4.3 Create a urls.py
file in your authapp and add the following code:
from django.urls import path
from .views import userLogin, dashboard, userlogout
urlpatterns = [
path('', userLogin, name='login'),
path('dashboard/', dashboard, name='dashboard'),
path('logout/', userlogout, name='logout'),
]
4.4 Add the following code snippet to the urls.py
file of your project:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('authapp.urls')),
path('accounts/', include('allauth.urls')),
]
4.5 Create a “templates” folder at the project level of your Django project, and then add the login.html
and dashboard.html
templates into this folder:
login.html
{% load socialaccount %}
Login
Login
dashboard.html
Dashboard
Welcome to Dashboard
Logout
Step 5: Running Django Project
To run your Django project with Google login functionality, execute the following command in your terminal:
python manage.py runserver
Access the site using the following URL: http://127.0.0.1:8000/