Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 4, 2022 11:31 am GMT

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

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  

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

# settings.pyINSTALLED_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

# main urls.py filefrom django.contrib import adminfrom django.urls import path, includeurlpatterns = [    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

python manage.py makemigrations
python manage.py migrate

7. Create a superuser

to create a super user use the following command

python manage.py createsuperuser

output

Username (leave blank to use 'rohit'): adminEmail address: admin@admin.comPassword: 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

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 urlshttp://127.0.0.1:8000/accounts/google/login/callback/http://localhost:8000/accounts/google/login/callback/
# add the following to javascript originshttp://127.0.0.1:8000http://localhost:8000

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.pySITE_ID = 1

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>

Original Link: https://dev.to/rohit20001221/google-authentication-in-django-the-simplest-way-3982

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To