Credit : KellyKiiru
OAuth, short for Open Authorization, is a mechanism that enables websites or applications to exchange user data with other platforms, all without necessitating the disclosure of a user’s password. It empowers users to access multiple websites with a single set of login credentials.
Prominent OAuth service providers include Google, Facebook, and GitHub. In this tutorial, we will explore the process of user registration within a Django application using Google OAuth as our chosen authentication method.
Prerequisites
To follow along with this article, you will need to have the following:
A GitHub account.
Python, pip and Django installed
Visual Studio Code — Integrated Development Environment(IDE)
Step 1 — Create and set up a new Django project
Create a folder(directory) and name it google-Oauth. Inside of this folder create a virtual environment:
python -m venv venv
You can name your virtual environment anything. In this case, I named it ‘venv’.
For Windows OS activate the virtual environment using:
venv\Scripts\activate
For Linux and mac OS use:
source venv/bin/activate
Or:
. venv/bin/activate
On activation, install django:
pip install django
Create a django project:
django-admin createproject auth_project .
Create a django app:
django-admin createapp auth_app
Add ‘auth_app’ to the INSTALLED_APPS array:
Apply and migrate this changes to SQLite:
python manage.py migrate
Step 2 — Install and set up django-allauth
Install the django-allauth
pip install django-allauth
Add it to the INSTALLED_APPS array:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites', //add this line too
'auth_app',
//all auth configurations
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google'
]
The last item of this array specifies the django-allauth provider you will use which in this case is google. django-allauth also supports other providers.
Add AUTHENTICATION_BACKENDS to settings.py at the bottom of your page:
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend'
]
Add SOCIALACCOUNT_PROVIDERS
configurations array to settings.py:
SOCIALACCOUNT_PROVIDERS = {
'google': {
'SCOPE' : [
'profile',
'email'
],
'APP': {
'client_id': os.environ['CLIENT_ID'],
'secret': os.environ['CLIENT_SECRET'],
},
'AUTH_PARAMS': {
'access_type':'online',
}
}
}
The SCOPE outlines the required parameters for Google APIs. In the absence of a specified scope, it will default to ‘profile.’ To enable background authentication refresh, configure AUTH_PARAMS[‘access_type’] as ‘offline.’
Add SITE_ID and redirect users to the base route after a successful login or logout.
SITE_ID = 2
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'
Step 3 — Create and configure templates
In this project we will use django templates to view our code. In auth_app, create a folder called ‘templates’. Django has an inbuilt mechanism that will find this templates folder.
Replace this TEMPLATES array in settings.py:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
with:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR/'templates'], //updated line
'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',
],
},
},
]
Inside of ‘templates’ folder in auth_app create an index.html file.
Add the following code to it:
{% load socialaccount %} //make sure to add this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1 style="text-align: center;"> My google OAuth Project </h1>
{% if user.is_authenticated %}
<p>Welcome. You are logged in as {{user.username}} </p>
{% else %}
<a href="{% provider_login_url 'google' %}">Login with Google</a>
{% endif %}
</body>
</html>
Step 4 — Configure Project URLs
Inside of auth_project/urls.py define the urlpatterns:
from django.contrib import admin
from django.urls import path,include
from django.views.generic import TemplateView // useful in displaying index.html template
from django.contrib.auth.views import LogoutView
urlpatterns = [
path('admin/', admin.site.urls),
path('app/',include('auth_app.urls')), //app_auth urls
path('', TemplateView.as_view(template_name='index.html')),
path('accounts/', include('allauth.urls')), // all OAuth operations will be performed under this route
path('logout', LogoutView.as_view()) // default Django logout view at /logout
]
Step 5— Create and configure a new Google APIs project
Head over to google developer APIs console and navigate to NEW PROJECT under ‘select project’
Set your app name and user support email in the OAuth Consent Screen
Switch to the Credentials tab and configure the following.
Note that its http and not https.
At this point create a .env and a .gitignore file in the root folder (google-Oauth) of your application. We will store our environment variables(secrets) in this file.
In your .gitignore file add the following lines. This will prevent git from pushing this code to GitHub as this folders will be ignored.
venv/
/.env
In your .env add the following:
This will be found in the Credentials tab:
To access the environment variables download load_dotenv from pip
pip install python-dotenv
In settings.py add this
import os
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()
This will make it possible for django to locate the environment variables. In this case:
SOCIALACCOUNT_PROVIDERS = {
'google': {
'SCOPE' : [
'profile',
'email'
],
'APP': {
'client_id': os.environ['CLIENT_ID'], // in .env file
'secret': os.environ['CLIENT_SECRET'], // in .env file
},
'AUTH_PARAMS': {
'access_type':'online',
}
}
}
Migrate this configurations:
python manage.py migrate
Step 6— Configuring admin site
Create super user:
python manage.py createsuperuser
Follow the prompts to create the superuser.
Run the server
python manage.py runserver
In your browser, open http://127.0.0.1:8000/admin and login with the superuser details and set the domain as well as display names like this.
Select social applications tab and configure it like this:
To test out if the installation was successful, log out on the top right and log in again but with google this time.
Since django already has a pre-made site(example.com) as seen above. The SITE_ID setting in settings.py might bring errors if its value is 1. Makes sure its value is 2.
SITE_ID = 2
On logging out, log in with google, your application will ask you to do so with your google account. This information will be saved in your auth_user table of your database. You can also confirm this by checking http://127.0.0.1:8000/admin/socialaccount/socialaccount/
Conclusion
In this article, you learned how to start and configure a django project as well as adding Google Oauth for auth_users.
You configured your google developer APIs console with the right details.
The code is available on GitHub. I hope this article was beneficial to you. If so, leave a github star.
Happy coding.