episyche logo

Episyche

React/Single sign-on (SSO)/

How to configure Google SSO in Django Rest Framework with React?

Published on

How to configure Google SSO in Django Rest Framework with React?
Single Sign On (SSO) gives your users convenient but secure access to all their web applications with a single set of credentials. This guide explains how we can configure Google SSO(Social Login) in the Django Rest Framework backend with React.

Introduction :

Django (Django rest Framework):

Django REST framework (DRF) is a powerful and flexible toolkit for building Web APIs.Its main benefit is that it makes serialization much easier. Django REST framework is based on Django's class-based views, so it's an excellent option if you're familiar with Django. To know more about relative links click here

Node.js :

Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that runs on a JavaScript Engine and executes JavaScript code outside a web browser. and NPM is a package manager for Node. js packages. The NPM program is installed on your computer when you install Node.js. To know more about relative links click here

React:

ReactJS is much easier to learn and use. ReactJS is a free and open-source front-end JavaScript library for building user interfaces based on UI components. to create interactive applications for mobile, web, and other platforms. To know more about relative links click here

Single sign-on(SSO):

Single sign-on (SSO) is a time-saving and highly secure user authentication process. SSO lets users access multiple applications with a single account and sign out instantly with one click.

How it Works:



how it's work?

Flow Diagram:


flow diagram

Prerequisites:

  • Python

  • Django REST Framework

  • google-auth

  • Node

  • React

Steps:

Step 1: Create Google client Id and client Secret

Check out this tutorial, to create a client Id and client secret.

Step 2: Set up a React project

Install Nodejs

Before we create React App we need to install node.js.

if you already installed node.js please ignore this step 2 and go to step 3

Step 3: Create a React-app

After installing Node.js open the terminal or command prompt and create the React app with the following commands

1npx create-react-app frontend

A sample screenshot of React app files is shown below.


Screenshot1

Step 4: Configure the React project to establish a connection with Google.

  • In your project, go to your /src directory and create a file called GoogleAuth.js.



Screenshot2

In src/GoogleAuth.js, add the following code.

  • For this example, we are using the useEffect,userRef. To know more about Next Routing click here.

1import React, { useEffect, useRef } from 'react' 2const loadScript = (src) => 3 new Promise((resolve, reject) => { 4 if (document.querySelector(`script[src="${src}"]`)) return resolve() 5 const script = document.createElement('script') 6 script.src = src 7 script.onload = () => resolve() 8 script.onerror = (err) => reject(err) 9 document.body.appendChild(script) 10 }) 11 12const GoogleAuth = () => { 13 14 const googleButton = useRef(null); 15 16 useEffect(() => { 17 const src = 'https://accounts.google.com/gsi/client' 18 const id = "Google Client Id" 19 20 loadScript(src) 21 .then(() => { 22 23 /*global google*/ 24 25 google.accounts.id.initialize({ 26 client_id: id, 27 callback: handleCredentialResponse, 28 }) 29 google.accounts.id.renderButton( 30 googleButton.current, 31 { theme: 'outline', size: 'large' } 32 ) 33 }) 34 .catch(console.error) 35 36 return () => { 37 const scriptTag = document.querySelector(`script[src="${src}"]`) 38 if (scriptTag) document.body.removeChild(scriptTag) 39 } 40 }, []) 41 42 function handleCredentialResponse(response) { 43 if (response.credential) { 44 var data = { "auth_token": response.credential } 45 fetch("http://127.0.0.1:8000/google/", 46 { 47 method: "post", 48 body: JSON.stringify(data), 49 headers: { 50 'Content-Type': 'application/json; charset=utf-8' 51 } 52 }) 53 .then((res) => res.json()) 54 .then((res) => { 55 document.getElementById("email_id").innerText=res['email'] 56 document.getElementById("auth_token").innerText=res['tokens'] 57 }) 58 59 } 60 } 61 62 return ( 63 <div id='google-login-btn'> 64 <div ref={googleButton} id='google-ref'></div> 65 <div> 66 <div> 67 <label>Email Id:</label> 68 <label id='email_id'></label> 69 </div> 70 <div> 71 <label>Auth token:</label> 72 <label id='auth_token'></label> 73 </div> 74 75 </div> 76 </div> 77 78 ) 79} 80 81export default GoogleAuth

Sample code for the src/GoogleAuth.js file can be found in the following Github URL.

  • Update the src/app.js file with the following code.

1import './App.css'; 2import GoogleAuth from './GoogleAuth'; 3 4function App() { 5 return ( 6 <div> 7 <GoogleAuth> 8 </GoogleAuth> 9 </div> 10 ); 11} 12 13export default App; 14

Sample code for the src/app.js file can be found in the following Github URL.

  • You can run your app via CLI with the following command and view it in your browser:

    1npm start

 

Front end results

Step 5: Set up a Django project.

1: Install Python

Python3.6 or above is needed to create a Django project, therefore please install the python and proceed to the next step.

2: Install Django:

Install the Django framework using the following command.

1pip install django

3: Create a Django Project:

Create a Django project using the below command.

1django-admin startproject backend

Step 6: Create a Django App:

After creating the Django project, then create the Django app

1python manage.py startapp accounts

A sample screenshot of Django project files is shown below.


Screenshot3

 

1: Install djangorestframework:

In this blog, we are using the Django Rest framework python library to create APIs, therefore the please install same to proceed further.

1pip install djangorestframework

2: Install django-cors-headers:

django-cors-headers library needs to establish a connection from the React frontend to Django API, hence please install the same using the below command.

1pip install django-cors-headers

3: Install google-api-python-client:

google-api-python-client python library is needed for Django to connect with google API. Therefore, please install the same using the following command.

1pip install google-api-python-client

Step 7: Configure the Django project to establish a connection with Google.

  • In backend/settings.py, add the following piece of code:

1GOOGLE_CLIENT_ID = <CLIENT_ID> 2SOCIAL_SECRET = <SOCIAL_SECRET>
1CORS_ORIGIN_ALLOW_ALL = True
1MIDDLEWARE = [ 2 'django.middleware.security.SecurityMiddleware', 3 'django.contrib.sessions.middleware.SessionMiddleware', 4 'django.middleware.common.CommonMiddleware', 5 'django.middleware.csrf.CsrfViewMiddleware', 6 'django.contrib.auth.middleware.AuthenticationMiddleware', 7 'django.contrib.messages.middleware.MessageMiddleware', 8 'django.middleware.clickjacking.XFrameOptionsMiddleware', 9 'corsheaders.middleware.CorsMiddleware', # <<< newly added line 10] 11

Sample code for the backend/settings.py file can be found in the following Github URL.

  • In your project, go to your /accounts directory and create a file called serializers.py.



Screenshot3

In /accounts/serializers.py, add the following code.

1from django.conf import settings 2from rest_framework import serializers 3from library.sociallib import google 4from library.register.register import register_social_user 5from rest_framework.exceptions import AuthenticationFailed 6 7class GoogleSocialAuthSerializer(serializers.Serializer): 8 auth_token = serializers.CharField() 9 10 def validate_auth_token(self, auth_token): 11 user_data = google.Google.validate(auth_token) 12 try: 13 user_data['sub'] 14 except: 15 raise serializers.ValidationError( 16 'The token is invalid or expired. Please login again.' 17 ) 18 print(user_data['aud']) 19 if user_data['aud'] != settings.GOOGLE_CLIENT_ID: 20 21 raise AuthenticationFailed('oops, who are you?') 22 23 user_id = user_data['sub'] 24 email = user_data['email'] 25 name = user_data['name'] 26 provider = 'google' 27 28 return register_social_user( 29 provider=provider, user_id=user_id, email=email, name=name) 30

Sample code for the /accounts/serializers.py can be found in the following Github URL.

  • Update the accounts/views.py file with the following code.

1from rest_framework.generics import GenericAPIView 2from .serializers import* 3from rest_framework.response import Response 4from rest_framework import status 5from rest_framework.permissions import AllowAny 6from rest_framework.decorators import permission_classes 7 8 9@permission_classes((AllowAny, )) 10class GoogleSocialAuthView(GenericAPIView): 11 12 serializer_class = GoogleSocialAuthSerializer 13 14 def post(self, request): 15 """ 16 POST with "auth_token" 17 Send an idtoken as from google to get user information 18 """ 19 20 serializer = self.serializer_class(data=request.data) 21 serializer.is_valid(raise_exception=True) 22 data = ((serializer.validated_data)['auth_token']) 23 return Response(data, status=status.HTTP_200_OK) 24

Sample code for the /accounts/views.py can be found in the following Github URL.

 

  • Create the sociallib and register directory in the following hierarchy.

    library → socaillib

    library → register.

  • After that, please create a google.py file inside the sociallib directory



Screenshot6

In library/sociallib/google.py, add the following snippet.

1from google.auth.transport import requests 2from google.oauth2 import id_token 3 4 5class Google: 6 """Google class to fetch the user info and return it""" 7 8 @staticmethod 9 def validate(auth_token): 10 """ 11 validate method Queries the Google oAUTH2 api to fetch the user info 12 """ 13 try: 14 idinfo = id_token.verify_oauth2_token( 15 auth_token, requests.Request()) 16 17 if 'accounts.google.com' in idinfo['iss']: 18 return idinfo 19 20 except: 21 return "The token is either invalid or has expired" 22

The sample code for the library/sociallib/google.py file can be found in the following Github URL.

 

  • Navigate to the library/register directory and create a file called register.py



Screenshot4

In library/register/register.py, add the following code.

1from rest_framework.authtoken.models import Token 2 3from accounts.models import User 4from django.conf import settings 5from rest_framework.exceptions import AuthenticationFailed 6 7 8def register_social_user(provider, user_id, email, name): 9 filtered_user_by_email = User.objects.filter(email=email) 10 11 if filtered_user_by_email.exists(): 12 if provider == filtered_user_by_email[0].auth_provider: 13 new_user = User.objects.get(email=email) 14 15 registered_user = User.objects.get(email=email) 16 registered_user.check_password(settings.SOCIAL_SECRET) 17 18 Token.objects.filter(user=registered_user).delete() 19 Token.objects.create(user=registered_user) 20 new_token = list(Token.objects.filter( 21 user_id=registered_user).values("key")) 22 23 return { 24 'username': registered_user.username, 25 'email': registered_user.email, 26 'tokens': str(new_token[0]['key'])} 27 28 else: 29 raise AuthenticationFailed( 30 detail='Please continue your login using ' + filtered_user_by_email[0].auth_provider) 31 32 else: 33 user = { 34 'username': email, 'email': email, 35 'password': settings.SOCIAL_SECRET 36 } 37 user = User.objects.create_user(**user) 38 user.is_active = True 39 user.auth_provider = provider 40 user.save() 41 new_user = User.objects.get(email=email) 42 new_user.check_password(settings.SOCIAL_SECRET) 43 Token.objects.create(user=new_user) 44 new_token = list(Token.objects.filter(user_id=new_user).values("key")) 45 return { 46 'email': new_user.email, 47 'username': new_user.username, 48 'tokens': str(new_token[0]['key']), 49 } 50

Sample code for the library/register/register.py file can be found in the following Github URL.

 

  • Add the accounts/urls.py file with the following content.

1from django.urls import path 2from .views import* 3 4urlpatterns = [ 5 path('google/', GoogleSocialAuthView.as_view()), 6] 7

An example screenshot of the Django project is shown below.

 

Screenshot5

The sample code for the accounts/urls.py file can be found in the following Github URL.

 

  • Finally, Run the Django application using the following command.

1 python manage.py runserver

 

A Sample GitHub repo, with all the required configurations, is given below.

Result:

After finishing all the steps mentioned above, please go to the web browser, and try to access the React application (i.e http://localhost:3000). An example output screenshot is given below.


Django results

Comments