DEV Community

Cover image for Google Authentication in Django The Simplest way
rohit20001221
rohit20001221

Posted on

Google Authentication in Django The Simplest way

Hi guys this time lets see how we can add google authentication to our django webapp

1. Setting up the django project

django-admin startproject GoogleAuthentication
Enter fullscreen mode Exit fullscreen mode

here we are creating a django project called GoogleAuthentication the name of project can be any thing literally.

2. Installing the django-allauth package

now let's install the required packages needed for adding google authentication to our web application

pip install django-allauth  
Enter fullscreen mode Exit fullscreen mode

3. Adding Authentication Backends in settings.py

you need to specify AUTHENTICATION_BACKENDS propery in your settings.py

# settings.py

# all the below property in your settings.py file for django allauth to work
AUTHENTICATION_BACKENDS = [
    # django's inbuild authentication backend
    'django.contrib.auth.backends.ModelBackend',

    # django's allauth authentication backend
    'allauth.account.auth_backends.AuthenticationBackend',
]
Enter fullscreen mode Exit fullscreen mode

4. Adding the required Apps in settings.py

you need to add the following apps to your settings.py note that you need to add django.contrib.sites to INSTALLED_APPS if it is not present

# settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',

    'django.contrib.sites', # <-- add the sites app here

    # apps needed for django all auth
    'allauth',
    'allauth.account',
    'allauth.socialaccount',

    # add the below app for google authentication to work
    'allauth.socialaccount.providers.google',



    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]
Enter fullscreen mode Exit fullscreen mode

5. Adding allauth urls to the main urls.py

include the django's allauth urls into our project using the code snippet below

# main 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')), #  <- include the allauth urls here
]
Enter fullscreen mode Exit fullscreen mode

6. Run the migrations

to run the migrations use the below two commands

python manage.py makemigrations
Enter fullscreen mode Exit fullscreen mode
python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

7. Create a superuser

to create a super user use the following command

python manage.py createsuperuser
Enter fullscreen mode Exit fullscreen mode

output

Username (leave blank to use 'rohit'): admin
Email address: admin@admin.com
Password: 
Password (again): 
Superuser created successfully.
Enter fullscreen mode Exit fullscreen mode

8. Create Google client-id and secret

now visit google developer dashboard by visiting the following link : google api console

now in the search bar search for Gmail and under Market Place select the Gmail API

Image description

now enable the Gmail API on clicking the Enable button

Image description

now visit the credentials page and click on " + CREATE CREDENTIALS " button and click on "OAuth Client ID"

Image description

now select the application type as Web as shown below

Image description

now name the application what ever you want i am naming it as Django Google Auth but the main thing we need to keep in mind is the redirect url and javascript origin

# add the following to redirect urls

http://127.0.0.1:8000/accounts/google/login/callback/
http://localhost:8000/accounts/google/login/callback/
Enter fullscreen mode Exit fullscreen mode
# add the following to javascript origins

http://127.0.0.1:8000
http://localhost:8000
Enter fullscreen mode Exit fullscreen mode

after adding the above urls click on create button

Image description

copy the client id and secret which appear on the screen

9. Configure the client id and secret

in the settings.py add the following line of code

# settings.py

SITE_ID = 1
Enter fullscreen mode Exit fullscreen mode

now login to the django admin page and edit the site example.com to localhost

Image description

now go to Social Applications and add the google client id and secret there

Image description

you can see above how we have added the cliend id and secret and also dont forget to add localhost to chossen sites

on visiting : http://127.0.0.1:8000/accounts/login/

you can see a link for login with google now you can login using google clicking on the link

LOGIN PAGE

Image description

GOOGLE AUTH

Image description

you can create custom login page using the below code snippet

<html>
<head>
  <!--Dont forget to replace with client id below-->
  <meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
</head>
<body>
  <div id="my-signin2"></div>
  <script>
    function onSuccess(googleUser) {
      console.log('Logged in as: ' + googleUser.getBasicProfile().getName());
    }
    function onFailure(error) {
      console.log(error);
    }
    function renderButton() {
      gapi.signin2.render('my-signin2', {
        'scope': 'profile email',
        'width': 240,
        'height': 50,
        'longtitle': true,
        'theme': 'dark',
        'onsuccess': onSuccess,
        'onfailure': onFailure
      });
    }
  </script>

  <script src="https://apis.google.com/js/platform.js?onload=renderButton" async defer></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)