Thought leadership from the most innovative tech companies, all in one place.

Django Social Authentication: Login With Google

How to sign in and sign out using Google and Django framework.

image

Login and Signup with Google And Django Framework

Hello, Django Developers!

My name is Rohit Kumar Thakur. I generally write about React Native, Django, Data Science, Machine Learning, and Python. In this article, I am going to show you how to use social authentication in Django applications. When you are building a web application, then adding Google authentication is the most common feature you can add. It will help users to log in to your website easily. So, without wasting any time let’s start this project. Here is the step by step video tutorial of this article:

Project Setup

Attention all developers seeking to make social connections and establish themselves while earning passive income — look no further! I highly recommend ‘From Code to Connections’, a book that will guide you through the process. Don’t miss out, grab your copy now on Amazon worldwide or Amazon India! You can also go for Gumroad

  • I always suggest starting a Django project in a virtual environment because it’s a good habit to practice.
  • Choose a directory. Open the terminal or command prompt window in that directory and start a virtual environment. Activate that virtual environment. I wrote a separate article on how to start a virtual environment in Windows and Linux. You can check if you need help.
  • After activating the virtual environment, install the following python library:
pip install django
pip install social-auth-app-django
  • Start a Django project:
django-admin startproject google
cd google
python manage.py startapp mainApp
  • Open this project in your favorite text editor. I mean VS Code. xd:)
Code

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',    'social_django',        #add this**
    'mainApp',              #add this**
]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**
]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**
            ],
        },
    },
]
#Add this at the bottom in settings.py**
#social app custom settings**
AUTHENTICATION_BACKENDS = [
    'social_core.backends.google.GoogleOAuth2',
    'django.contrib.auth.backends.ModelBackend',
]LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_URL = 'logout'
LOGOUT_REDIRECT_URL = 'login'SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '##################################'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '###########################'

In the settings.py. We need to add a few lines of code to INSTALLED*APPS, MIDDLEWARE, and TEMPLATES sections. After that, we have to add a few lines of code at the bottom as shown above. 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](http://twitter.com/login%5Frequired)
def home(request):
    return render(request, 'home.html')

In views.py, first, we are going to import all the required libraries. After that, write two functions to render the login and home screen. Now inside the mainApp directory. Make a new directory “templates”. Inside the templates directory, make three new files: base.html, login.html, home.html Make a static folder too. Inside the mainApp directory. And inside the static directory, make a file “index.css” You can customize the CSS part on your own if you want. But for a minimal UI reference, you can add the following codes to the index.css file.

.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;
}

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>

This is the code of the base.html file. We are going to take reference and relative tag elements in login.html and base.html. 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 class="btn btn-primary mb-2">
      <a href="{% url 'social:begin' 'google-oauth2' %}">Login With Google</a>
    </button>
  </div>
</div>
{% endblock %}

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 %}

This is the basic code of login and home screen. After the successful login, we are going to display the name of the user on the home screen.

google/urls.py

from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
from mainApp import viewsurlpatterns = [
    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'),
]

Add the URLs in the main directory.

Configure Google Developer Console

Now we have to do only one thing. Let’s set up Google Developer Console. I recommend you watch the video after 18:24.

  • 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 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.
  • If you checked the video then make sure to hit the subscribe button. I make cool Django and react native applications. Your support will be admired. Copy and paste the client id and client secret to your settings.py.
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '##################################'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '###########################'

Now, Open your terminal or command prompt and migrate the Django application.

python manage.py makemigrations
python manage.py migrate
python manage.py runserver

Now click on the “login with google” button. You are good to go now.

Github code Link

Thanks for reading.




Continue Learning