How To Add Social Authentication Using Django-Allauth To Your Django Project (Google OAuth Example)
In this tutorial, you will learn how to integrate the Django-Allauth package into a Django project to add social authentication to your app. It’s a nice way to reduce friction, increase sign-ups, ease the log-in process, and improve overall security and user experience.
We will create simple Django templates for sign-up, log-in, and forgot password forms and enable the Google OAuth2 provider for sign-up and log-in. We will also configure the project to use the email address as the username to keep things simple.
This will give you a basic understanding of how the Django-Allauth package works, so you can integrate it with your existing app and add any social authentication providers supported by the package.
If you’re starting to build a Django app, consider Pegasus SaaS boilerplate. This is what I use to start Django projects. It includes Django-Allauth (and many other packages) and HTML templates based on your choice of a CSS framework (Bootstrap, Tailwind, Bulma). Instead of wasting time building everything from scratch, Pegasus can help you hit the ground running so you can build and launch your app within days.
Before we begin
This article assumes you already have Python and Django installed. If you need help installing Django, here are two resources:
Step 1: Install Django-Allauth
First, let’s install the Django-Allauth package using Pipenv. Open the terminal and run the following command:
pipenv install django-allauth
Step 2: Configure Django-Allauth
After installing the package, open the Django project’s settings.py
file and add allauth
and allauth.account
to the INSTALLED_APPS
list:
INSTALLED_APPS = [
# ...
'allauth',
'allauth.account',
# ...
]
Next, we need to add the following lines to the settings.py
file to configure the authentication backends and specify that we want to use email as the username:
AUTHENTICATION_BACKENDS = (
'allauth.account.auth_backends.AuthenticationBackend',
'django.contrib.auth.backends.ModelBackend',
)
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_VERIFICATION = 'optional'
LOGIN_REDIRECT_URL = '/'
One thing to note, ACCOUNT_EMAIL_VERIFICATION
has three options:
- mandatory — email verification is required, and the user can’t go past the email verification screen.
- optional — email verification is optional, and the user can continue within the app but will receive an email to verify the email address.
- none — disables email verification.
Now, include allauth.urls
in the project’s urls.py
file:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('allauth.urls')),
# ...
]
Step 3: Create templates
In this step, we will create simple templates for sign-up, login, and forgot password forms. If you’re using Pegasus SaaS boilerplate, all these pages are already created using your chosen CSS framework.
In your Django project, create a new folder named templates
, and inside the templates
folder, create the following file:
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}My Django App{% endblock %}</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
<a class="navbar-brand" href="#">My Django App</a>
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="{% url 'account_login' %}">Login</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'account_signup' %}">Sign up</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'account_reset_password' %}">Forgot Password</a>
</li>
</ul>
</nav>
</header>
<main>
<div class="container">
{% block content %}
{% endblock %}
</div>
</main>
</body>
</html>
This base.html template uses the Bootstrap framework for styling. The {% block content %}
and {% endblock %}
tags define a content block that can be overridden by other templates that extend this base template. In this case, the signup.html
, login.html
, and password_reset.html
templates will replace the content block with their respective form contents.
Now, inside templates
folder create another folder named account
. Inside the account
folder, create the following HTML files:
signup.html
{% extends "base.html" %}
{% block content %}
<h2>Sign up</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Sign up</button>
</form>
{% endblock %}
login.html
{% extends "base.html" %}
{% block content %}
<h2>Login</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
{% endblock %}
password_reset.html
{% extends "base.html" %}
{% block content %}
<h2>Forgot Password</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Reset password</button>
</form>
{% endblock %}
You now have a fully functional user authentication system in your Django app. If you don’t need social authentication, you’re done.
Step 4: Enable Google OAuth2 provider
To enable the Google OAuth2 provider for sign up and log in, we must get API credentials in Google Developer Console:
1. Obtain OAuth2 credentials from Google Developer Console
- Visit the Google Developer Console.
- Create a new project, or select an existing project.
- Go to the ‘OAuth consent screen’ tab and fill in the required information.
- Go to the ‘Credentials’ tab, click ‘Create credentials,’ then choose ‘OAuth client ID.’
- Select ‘Web application,’ fill in the required information, and click ‘Create.’
- Note down the generated ‘Client ID’ and ‘Client Secret.’
2. Add social account providers to Django
In your Django project’s settings.py
file, add allauth.socialaccount
and allauth.socialaccount.providers.google
to the INSTALLED_APPS
list:
INSTALLED_APPS = [
# ...
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
# ...
]
3. Configure Google OAuth2 provider
Add the following lines to your settings.py
file to configure the Google OAuth2 provider:
SOCIALACCOUNT_PROVIDERS = {
'google': {
'APP': {
'client_id': '<your-client-id>',
'secret': '<your-client-secret>',
'key': ''
},
'SCOPE': [
'profile',
'email',
],
'AUTH_PARAMS': {
'access_type': 'online',
}
}
}
You can add this right below INSTALLED_APPS
. Replace <your-client-id>
and <your-client-secret>
with the credentials you obtained from the Google Developer Console.
4. Update project URLs
Include allauth.socialaccount.urls
in your Django project’s urls.py
file:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('allauth.urls')),
path('accounts/', include('allauth.socialaccount.urls')),
# ...
]
5. Update templates
Update the signup.html template to add a “Sign up with Google” button:
{% extends "base.html" %}
{% block content %}
<h2>Sign up</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Sign up</button>
</form>
<p>Or</p>
<a href="{% provider_login_url 'google' %}">Sign up with Google</a>
{% endblock %}
Update the login.html
template to add a “Sign in with Google” button:
{% extends "base.html" %}
{% block content %}
<h2>Login</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
<p>Or</p>
<a href="{% provider_login_url 'google' %}">Sign in with Google</a>
{% endblock %}
You have successfully integrated Django-Allauth with Google OAuth2 provider into your Django project. Your users can sign up and log in using their email addresses or their Google accounts.
When you’re done, your project’s file structure should look like this:
my_django_project/
│
├── my_django_project/
│ ├── __init__.py
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
│
├── templates/
│ ├── base.html
│ └── account/
│ ├── login.html
│ ├── signup.html
│ └── password_reset.html
│
├── Pipfile
├── Pipfile.lock
└── manage.py
New To Django?
If you’re new to Django, as I was, you may be looking for good resources to learn how to use Django to build apps. The best resources that helped me learn Django with easy-to-follow instructions and code are the three ebooks written by William S. Vincent (he keeps them up-to-date):
Django for Beginners laid a solid foundation for me to pick up all other Django (and Python) concepts. Start with that ebook. That’s what I did.
If you want to be notified of new stories related to Django, follow Powered by Django here on Medium, or you can follow me to learn more about digital marketing in addition to Django.
This article includes affiliate links.