Google Authentication in Django The Simplest way
Tags: django, googleauth, djangoallauth
Published: 2022-04-04 11:31:39

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

## 1. Setting up the django project

```bash
django-admin startproject GoogleAuthentication
```

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

```bash
pip install django-allauth  
```


## 3. Adding Authentication Backends in settings.py

you need to specify **AUTHENTICATION_BACKENDS** propery in your **settings.py**

```python
# 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',
]
```

## 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

```python
# 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',
]
```

## 5. Adding allauth urls to the main urls.py

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

```python
# 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
]
```

## 6. Run the migrations

to run the migrations use the below two commands

```bash
python manage.py makemigrations
```

```bash
python manage.py migrate
```

## 7. Create a superuser

to create a super user use the following command

```bash
python manage.py createsuperuser
```

**output**

```python
Username (leave blank to use 'rohit'): admin
Email address: admin@admin.com
Password: 
Password (again): 
Superuser created successfully.
```

## 8. Create Google client-id and secret

now visit google developer dashboard by visiting the following link : [google api console](https://console.cloud.google.com/apis/dashboard)

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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wkoyqk2lpoi6yw5w00ym.png)

now enable the Gmail API on clicking the **Enable** button


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8gjih16y2ffaddz0kulj.png)


now visit the [credentials](https://console.cloud.google.com/apis/credentials) page and click on " + CREATE CREDENTIALS " button and click on "OAuth Client ID"


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/scy6xvpy9ycoovjbh78b.png)

now select the application type as Web as shown below


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wctla26f8jevyrpo8yi6.png)


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**

```bash
# add the following to redirect urls

http://127.0.0.1:8000/accounts/google/login/callback/
http://localhost:8000/accounts/google/login/callback/
```

```bash
# add the following to javascript origins

http://127.0.0.1:8000
http://localhost:8000
```

after adding the above urls click on create button


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tcb30i6gwevyh48f46wl.png)

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

```python
# settings.py

SITE_ID = 1
```

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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ob8esmujbdz8o9jjauz3.png)

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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0midxn8balu40d0z8h31.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w7id2tj228ihj04njrgi.png)


**GOOGLE AUTH**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pa3aow0yfq5wzo2te2m7.png)


**you can create custom login page using the below code snippet**

```html
<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>
```