Google Authentication in Django | Implement Login Functionality using Google in Django

In this Python Django tutorial, we will learn about Google authentication in Django and how to implement login functionality using Google in Django. We will learn how to use the built-in functionalities of Django to create a Google Login system.

To create a Google Login System in Django, we will use the social-auth-app-django package which we have to install in the system.

Create Login Functionality using Google in Django using social-auth-app-django

In this section, we’ll learn how to use Django’s built-in feature to create a Google authentication system. I’ll guide you through it step by step using an example.

1. Create Virtual Environment

Creating a virtual environment is good practice for a developer before installing Django.

Syntax

python -m venv venv_name

Example: Here I create a virtual environment as myenv in a Windows terminal.

python -m venv myenv

After creating venv, you need to activate it.

myenv\Scripts\activate

2. Install Django and social-auth-app-django package in the Virtual Environment

After activation of the virtual environment, you have to install Django in your virtual environment.

pip install django

Also, you need to install social-auth-app-django in your virtual environment to use the inbuilt features of Django.

pip install social-auth-app-django
social authentication in django

3. Create Django Project

If you’re starting a new project, first you have to create a new Django project. The command to create a new project is as follows:

django-admin startproject project_name

Example: Here I create a new project named google.

READ:  How to use Tkinter Filedialog in Python [3 Examples]

Command:

django-admin startproject google .

4. Create Django Application

After the creation of the project, you have to create an application for a well-organized project structure in Python Django.

Syntax:

python manage.py startapp app_name

Example: Here I create an application as mainApp.

Code

python manage.py startapp mainApp.

5. Add Necessary settings in your Django Project

In your project folder, there is one file called settings.py, so check all these settings in your file.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'social_django',       # Add this Line
    'mainApp',   # Add your application 
]

# Add this section 
AUTHENTICATION_BACKENDS = [
    'social_core.backends.google.GoogleOAuth2',
    'django.contrib.auth.backends.ModelBackend',
]

# Add this part in your Middleware
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'social_django.middleware.SocialAuthExceptionMiddleware' # Add this line
]

# Add this line in TEMPLATES :
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',
                'social_django.context_processors.backends',  # Add this line 
            ],
        },
    },
]

SOCIAL_AUTH_GOOGLE_OAUTH2_KEY=' # Add your client id here '
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '#Add your secret key here'
SOCIAL_AUTH_GOOGLE_OAUTH2_REDIRECT_URI = 'http://localhost:8000/complete/google-oauth2/'
Python django Google authentication
Add Google Login to your Django Project

6. Create Django Templates

In your mainApp, you have to create one folder called templates where you will maintain the HTML files of your project for the user interface. Then we will create 3 HTML files inside the templates folder.

  1. base.html
  2. login.html (name should be same)
  3. home.html
Google authentication in django using social-auth-app-django

templates/base.html: This file serves as the master template for the other HTML files of the project. It includes the common structure and elements which can be useful for other templates.

Code for base.html :

{% load static %} 
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
        <link rel="stylesheet" href="{% static 'index.css' %}" />
        <title>Django Social Auth</title>
</head>
    <body>
        <div class="container-fluid">
            <div>
                <h1 class="text-white text-center">{% block title %}{% endblock %}</h1>
                <div class="card p-5">
                    {% block content %} 
                    {% endblock %} 
                </div>
            </div>
        </div>
    </body>
</html>

templates/login.html

2. login.html: This template is often used to create a user interface for the login functionality and this file is part of the default authentication views provided by ‘django.contrib.auth‘.

READ:  Python Turtle Square - Helpful Guide

Code for login.html

{% extends 'base.html' %} 
{% block title %}Sign in{% endblock %} 
{% block content %} 
    <div class="row">
        <div class="col-md-8 mx-auto social-container my-2 order-md-1">
            <button>
                <a href="{% url 'social:begin' 'google-oauth2' %}?next={{ request.path }}">Login With Google</a>

            </button>
        </div>
    </div>
{% endblock %}

Note: The name of the file login.html is mandatory to give the same name because we are using django inbuilt class for the login.html template from ‘django.contrib.auth‘.

Code for home.html

{% extends 'base.html' %} 
{% block title %}HOME{% endblock %} 
{% block content %} 
    <div class="row">
        <div class="col-sm-12 mb-3">
            <h4 class="text-center">Welcome {{ user.username }}</h4>
        </div>
    </div>
{% endblock %}

We’ve also created one directory called static inside mainApp and CSS inside the static folder. Where we will create one CSS file.

index.css

.container-fluid {
    height: 100vh;
    background-color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
}
.container-fluid > div {
    width: 85%;
    min-width: 300px;
    max-width: 500px;
}
.card{
    width: 100%;
    background-color: #282c34;
}
.social-container {
    display: flex;
    flex-direction: column;
    justify-content: center;
}
.btn a, .btn a:hover {
    color: white;
    text-decoration: none;
}

7. Create views for login and home in the Django

In your application (mainApp), there is one file called views.py. In that file, we will connect our HTML templates to the Django Project.

Code for mainApp/views.py

from django.shortcuts import render
from django.contrib.auth.decorators import login_required
# Create your views here.
def login(request):
    return render(request, 'login.html')
@login_required
def home(request):
    return render(request, 'home.html')

8. Set your project urls.py for Google Login

In your project (google), there is one file named urls.py, you have to create URLs for login, logout, and home views. Also, you have to include a built-in class from social_django.urls.

from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
from mainApp import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('login/', views.login, name='login'),
    path('logout/', auth_views.LogoutView.as_view(), name='logout'),
    path('social-auth/', include('social_django.urls', namespace='social')),
    path("", views.home, name='home'),
]

9. Setup your Google Developer Console

In your settings.py you have to provide SOCIAL_AUTH_GOOGLE_OAUTH2_KEY and SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET. To get these things, you have to setup your Google Developer Console. Let’s see how to setup step by step.

  • Go to Google Developer Console.
  • Select your country and confirm the terms and services.
  • Click on Select a new project
  • Click on New Project
  • Project name: test. Click on continue.
  • Click on credentials.
  • Click on “Configure Consent Screen”
  • Select External. Click on Create.
  • Enter app name: testapp. Add your support email
  • At the bottom. Add developer contact information. Click on save and continue.
  • Click on save and continue 2 times. Then click on Back to the dashboard.
  • Again click on credentials.
  • Click on Create credentials. Click on OAuth Client ID.
  • Select the Application type as web.
  • Add two Authorized JavaScript origin URLs: http://localhost:8000 and http://127.0.0.1:8000
  • Authorized Redirect URIs: http://localhost:8000/social-auth/complete/google-oauth2/
  • Click on Create.
  • Copy and paste the client id and client secret to your settings.py.
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '# enter your key here'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '# enter your secret code here'

10. Migrate the tables

You have to migrate the default tables of Django, after that, you can run your project.

READ:  How to Copy a NumPy Array to Clipboard through Python [3 Methods]

Code for migration:

python manage.py makemigrations
python manage.py migrate

Code to run the server

python manage.py runserver

Output :

How to create Google Login in Python Django
How to integrate google login in django

Conclusion

In this Python Django tutorial, we’ve covered Google Authentication using social-auth-app-Django. Also, we will learn how to manage template structure for Google authentication and how to create a Google Developer Console where you will get your Client_id key and Secret Key, which is required for the Google Authentication System in Django.

You may like to read: