Introduction
Many modern web apps are using social authentication methods as an authentication option. Social authentication involves using third party apps, usually social media apps or Google, as a sign up or login option. The use of third-party apps such as Google, Facebook, Twitter/X, or Github to authenticate users improves user experience. Users do not have to go through the long and tedious process of manually creating an account. As a result, authentication is fast and effortless.
Moreover, on the business side, authenticating with trusted third parties significantly buffers a web app’s security. Facebook, X, and Google have rigorous authentication processes themselves. If a prospective user account is deemed as "not malicious" by Google, then the account most likely poses a lower security risk for your app.
This article walks Django developers through the process of adding Google social sign in as a login option to their authentication flow. Let us dig in.
Prerequisites
- A beginner-level understanding of Django web framework.
- A VS Code editor installed.
Building your Project
Getting Started
We are going to create a sample Django project with which to integrate Google social authentication. Proceed to open your VS Code editor then create a directory called Google-OAuth2
, which will host your entire application code.
If you already have a project and only need to start integrating Google social authentication, jump to here.
Setting up your Development Environment.
You need to create a Python virtual environment to isolate and install software dependencies you will need for this project. We obviously need to install the Django framework itself. Then we will install a package known as django-allauth
. django-allauth is a Django project, available on Github. The project contains all the necessary routes (URLs), logic (views) and rendering mechanisms (HTML templates) that facilitate social login with major third parties such as Google, Twitter and Facebook. You can check out the project for a deeper understanding.
Open a new VS code terminal and ensure you are inside your project directory. Create a Python virtual environment using the venv
python module like this:
-m venv venv
info: The first
venv
command line argument is the Python virtual environment module while the secondvenv
argument is a custom name you give as an identifier of your virtual environment. You could name your virtual environment anything you want—env, myenv, env1, my_env, etc.
After the Python interpreter has successfully created a virtual environment for you, you should see a new directory named as the custom name of your virtual environment inside your Google-OAuth2
folder. Now activate the virtual environment by running the command venv\Scripts\activate
. You should see your virtual environment name, enclosed by parentheses, preceding your terminal’s command prompt:
users\user\Desktop\Google-OAuth2:
Perfect. Now install django and django-allauth inside the environment using pip.
pip install django django-allauth
Warning: You can install several packages using one pip command like above. However, it is best practice to install a package at a time. If one fails to install, it is easier to pin-point which package failed.
Now we Build
Inside your root directory, create a Django project like this:
startproject core .
Django will create a new directory called core
in the current working directory.
warning: Remember to include the period at the end. Otherwise, Django will create a project directory called
core
within another directory with the same name.
Next, create an application called authentication
:
manage.py startapp authentication
The above command invocation will create an app directory called authentication
at the same level as your project directory core
. Proceed to include your new application in the list of INSTALLED_APPS
section of the newly created settings.py
file:
# core/settings.py
INSTALLED_APPS = [
...
'authentication',
...
]
Create a User Data Model
Next, you need to create a user data model that defines how your application will store user information.
Think about the utility of the application you are creating for a minute. Why are you integrating Google social authentication in the first place? You want to extend the built-in user model by allowing a user to log in using their email instead of a username. Remember that social authentication is usually built on top of the traditional Django authentication system. For the traditional authentication, a user registers with a username, email (optional), and password as primary credentials. Therefore, your user data model should have all these fields.
Django ships with a built-in user model, a Python class object, called User
. The model has the three primary fields above in addition to other fields. You can extend the User
model by creating your own custom fields and methods to suit your unique project needs.
For instance, the default username field in the built-in model requires a username. You may override this condition if you want your users to use email addresses as their usernames instead, as we will do in this project.
To include extra custom fields, your User
class object should inherit from another Django class object called AbstractUser. This superclass allows you to include custom fields and customize the default fields.
With this information in mind, edit your authentication/models.py
file like this:
# authentication/models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
username = models.CharField(max_length=100)
email = models.EmailField(max_length=100)
password = models.CharField(max_length=100)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
Our custom user model extends the built-in AbstractUser
model. Even though username, email and password fields exist in the built-in model, you explicitly redefine them here to customize the allowable lengths for the username, email, and password strings you want to accept from the user during registration.
Furthermore, you override the default username field to use an email instead of a username.
Next, to use your custom user model, you need to register your model in settings.py
file. Head over to core/setttings.py
and add this line:
# Custom user model
AUTH_USER_MODEL = 'authentication.CustomUser'
Note: This directive overrides the default
User
by stating the path to the custom model, which is in the authentication app.
Next, you need to initialize and apply a database schema to an SQLite database that ships with Django. Run the following two commands in your VS Code terminal:
Python manage.py makemigrations
Python manage.py migrate
Proceed to register your custom user model with the admin so you can access and edit your database entries as admin:
# authentication/admin.py
from django.contrib import admin
from django.contrib.auth import get_user_model
CustomUser = get_user_model()
admin.site.register(CustomUser)
Finally, using a VS Code terminal, create a superuser account that can access the admin dashboard:
python manage.py createsuperuser
Run a development server:
python manage.py runserver
A local development server will start on port 8000. Visit http://127.0.0.1:8000/admin
to log into the admin panel. You should see your model under Models. You can create a few user entries for testing purposes.
Integrate Google OAuth2
Time to bring in the big guns. As you have already installed the django-allauth
dependency, let’s proceed to configure our backend to support authentication with Google.
django-allauth
is a django project similar to the one you're building here, with several apps. You therefore need to register the required django-alluth
apps in your INSTALLED_APPS
section.
Add the following django-alluth apps to the section. You could label the apps as "allauth apps" to distinguish them from other installed apps:
INSTALLED_APPS = [
…
#allauth apps
'allauth',
'allauth.account',
'allauth.socialaccount',
'alluth.socialaccount.providers.google',
…
Next, you need to update the middleware settings under the MIDDLEWARE
section. Insert this middleware at the bottom of the middleware list:
MIDDLEWARE = [
...
'allauth.account.middleware.AccountMiddleware',
]
Next, you need to configure AUTHENTICATION_BACKENDS
. When you issue this directive in the settings.py, you are providing a way for your project to handle the authentication credentials passed into sign up and login endpoints.
Now, by default, Django uses ModelBackend
to parse authentication credentials, i.e., it verifies your sign up or login schema against the built-in or custom user model.
Note: When you initialize a Django project, the
AUTHENTICATION_BACKENDS
directive is not explicitly stated. (You will not see this directive when you open your settings.py file). Nonetheless, it's default value isModelBackend
. If you do not need to use any other authentication backend, it is needless to explicitly state this directive. Django will use theModelBackend
.
django-allauth
relies on its own authentication backend that extends the default. Therefore, you need to provide an additional authentication backend to cater to allauth
authentication. Hence, you must explicitly state the AUTHENTICATION_BACKENDS
directive. Add the following setting:
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',
]
Next, add social provider settings:
SOCIALACCOUNT_PROVIDERS = {
'google': {
'SCOPE': [
'profile',
'email',
],
'AUTH_PARAMS': {
'access_type': 'online',
},
'OAUTH_PKCE_ENABLED': True,
}
}
Notice that the above are Google provider specific settings. allauth
provides similar settings for tons of other third-party authentication providers. See a full list here.
And finally for settings.py, add these extra allauth
email account configurations:
# Django allauth config
SITE_ID = 1
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_AUTHENTICATION_METHOD = 'email'
Include allauth URLs
django-allauth
ships with its URLs. You can use or override the URLs in your project. For this project, you will be using some of these default URLs. More specifically, you will utilize the URL that allows for login with Google, You can visit the documentation for more information.
In your project level urls.py
file add this code:
# core/urls.py
from django.urls import path, include
from django.contrib import admin
urlpatterns = [
path('admin/', include('admin.site.urls')),
path('accounts/', include('allauth.urls')),
]
You are all set to use django allauth's URLs.
Set up an App in Google Developer Console
You need to set up an app in Google Console to enable users of your application authenticate with Google. The process involves two steps:
- Configuring an OAuth consent screen
- Setting up Credentials
OAuth consent screen
- Visit Google developer console.
- Create a new project with a suitable name from the dropdown menu.
- Select to use the project you have just created from the dropdown menu.
- In the displayed window, select OAuth consent screen and select the External option, then hit Create.
- Fill in only the App information and Developer information details under Oauth2 consent screen.
- Click on Save and continue.
- Click on Save and continue button for both Scopes and Test users forms without filling in anything.
- Confirm your Oauth2 details in the Summary section then click on Back to dashboard.
Set up Credentials
- Locate Credentials under APIs and Services
- Click on Create Credentials and select OAuth Client ID from the dropdown options.
- Select Web application for the Application type field. You could use the default name under the Name field or provide a suitable name.
-
Select ADD URI under Authorized JavaScript Origins to add a Uniform Resource Identifier (URI).
Info: Adding a URI ensures only permitted domains can send requests to your OAuth2 app from a browser. Since you will be testing your Django app in development, add this local host URI:
http://127.0.0.1:8000
-
Select ADD URI under Authorized Redirect URIs and add the following URI:
http://127.0.0.1:8000/google/login/callback/
Info:This is the callback URL where Google will redirect to after a user grants or denies your application permission to authenticate with their Google account.
Hit the Create button and wait for a few seconds for your app to be ready. Your new app will generate a Client ID and Client secret. In the resulting window, download the JSON for these details or copy and paste the Client ID and Client secret somewhere. You will need these details in a few.
Set up a Social Account Provider
Next, you need to set up a Social Account with the client ID and secret you generated earlier in your admin console. Login in to the admin via http://127.0.0.1/8000/admin
and locate the SOCIAL ACCOUNTS
section. Under this section, click on SOCIAL APPLICATIONS
then select ADD SOCIAL APPLICATION
.
Under Provider, if you click on the dropdown icon, you will notice that Google
is already available as a provider. This is because we already configured Google as a provider in our settings.py file
, when we added this line:
# core/settings.py
INSTALLED_APPS = [
...
'alluth.socialaccount.providers.google',
]
Just to test it out, you could try commenting out this line and refreshing your current admin view. Google will disappear under providers.
Back to adding a social application, uncomment the above code if you commented it out. Select Google under provider and provide a suitable name for the Name field. For this purpose, call your social application Google
.
Next, under Client id, paste the Client ID from Google console. Similarly, paste your Google console's secret key under Secret key. Finally, click on Save to save your social application credentials.
Everything is now set.
Testing and Troubleshooting
Now visit http://127.0.0.1:8000/accounts/google/login
.
Try logging in via the Google third party.
django-allauth
will hand over the authentication process to Google. Google will use the app you configured in the console to carry out the authentication for the Google account you select. Google will then return a response to your allauth
app via the callback URL you provided in Google console's Authorized Redirect URIs section. Allauth will then handle the rest of the authentication flow from here.
If you had issued a LOGIN_REDIRECT_URL
directive in your settings.py
file, allauth
will redirect the user to the URL provided for login redirect. For instance, you could create a home page and pass its URL as the LOGIN_REDIRECT_URL
. Your app will redirect all successfully logged in users to your home page.
Conclusion
This tutorial walks the reader through the process of integrating social authentication into a Django web application using Google. The process involves defining a suitable user data model, configuring allauth
in your Django app, and setting up an app in Google console, pointing it to your Django app. Finally you need to test the authentication flow. You can extend this application by integrating other third party authentication flows such Facebook, X, or Github using the django-allauth package. Hope this helps. Happy coding!
Top comments (0)