Unlocking Seamless Authentication: A Comprehensive Guide to Google Login with Django and React Part-1
Embark on a journey to enhance the user authentication experience in your web applications by delving into the powerful synergy of Google OAuth2, Django, and React. Our latest blog is your comprehensive guide to seamlessly integrating Google OAuth2 authentication into your Django backend while harnessing the dynamic capabilities of React on the frontend.
We use these package in this tutorial
- https://drf-social-oauth2.readthedocs.io/en/latest/
- https://pypi.org/project/python-dotenv/
- https://pypi.org/project/django-cors-headers/
Getting Django restframework ready and running
Make a virtual env named venv
python3 -m venv env
Activate it by
source env/bin/activate
Make requirements.txt
touch requirements.txt
Add these to requirements.txt
Django==3.1.2
djangorestframework==3.12.1
drf_social_oauth2==1.0.9
python-dotenv==1.0.0
django-cors-headers==3.7.0
Install requirements.txt and start a new project
pip install -r requirements.txt
django-admin startproject <your project name> .
Now open your project /settings.py and add these third party apps to your registered apps
'rest_framework',
'oauth2_provider',
'social_django',
'drf_social_oauth2',
'corsheaders',
Then in the middleware section add these
'corsheaders.middleware.CorsMiddleware',#add
'django.middleware.common.CommonMiddleware',#add
Add this to allow react app to make requests from port 3000 this helps react app to make requests on backend
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
]
Include social auth urls to your project/urls.py :
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('auth/',include('drf_social_oauth2.urls',namespace='drf')) # add this line to include the auth urls
]
Add templates conf to settings.py
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",
# for social auth
"social_django.context_processors.backends",
"social_django.context_processors.login_redirect",
],
},
},
]
Add TEMPLATE_CONTEXT_PROCESSORS in settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
...
'social_django.context_processors.backends',
'social_django.context_processors.login_redirect',
)
enable the authentication classes for Django REST Framework by default or per view by updating the REST_FRAMEWORK and AUTHENTICATION_BACKENDS entries in your settings.py:
REST_FRAMEWORK = {
...
'DEFAULT_AUTHENTICATION_CLASSES': (
...
# 'oauth2_provider.ext.rest_framework.OAuth2Authentication', # django-oauth-toolkit < 1.0.0
'oauth2_provider.contrib.rest_framework.OAuth2Authentication', # django-oauth-toolkit >= 1.0.0
'drf_social_oauth2.authentication.SocialAuthentication',
),
}
AUTHENTICATION_BACKENDS = (
...
'drf_social_oauth2.backends.DjangoOAuth2',
'django.contrib.auth.backends.ModelBackend',
)
To include Google Oauth authentication add these to settings.py:
AUTHENTICATION_BACKENDS = (
# Google OAuth2
'social_core.backends.google.GoogleOAuth2',
# drf-social-oauth2
'drf_social_oauth2.backends.DjangoOAuth2',
# Django
'django.contrib.auth.backends.ModelBackend',
)
# Define SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE to get extra permissions from Google.
SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
]
Make enviroment variables in a .env file on root folder where your manage.py is placed and add your google key and secret to it
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY=126073961034-gi3pldgf147r7dirmioe1ld.apps.googleusercontent.com
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET=GOCSPX--zfssbUxCQN9pXlLq4dBI
we using python-dotenv for getting env vars
#add these on top of settings.py
from dotenv import load_dotenv
import os
load_dotenv()
#import your creditionals like this in settings.
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = os.environ.get("SOCIAL_AUTH_GOOGLE_OAUTH2_KEY")
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = os.environ.get("SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET")
Now migrate the DB changes :
python manage.py migrate
Create superuser for creating a new application for auth by adding username, email, password:
python manage.py createsuperuser
Now runserver and open this url and fill your creditionals that we created http://127.0.0.1:8000/admin/
Now you need your client_id and client_secret to get these We need to make a new application in DJANGO OAUTH TOOLKIT / Applications
Follow these step:
- Click on applications under DJANGO OAUTH TOOLKIT section
- Click on add applications
- Then u have to copy your key and Id from the next page
- select the user that we created as superuser in first field
- client type should be Confidential
- Authorization grant type will Resource owner password based
- Name field: you can give it any name
- Hit save button
Now go to http://127.0.0.1:8000/auth/convert-token and test it
We completed the backend you can test it with the command and give your credential in the command (You can skip this we will discuss this in next blog).
$curl -X POST -d "grant_type=convert_token&client_id=<django-oauth-generated-client_id>&client_secret=<django-oauth-generated-client_secret>&backend=google-oauth2&token=<google_token>" http://localhost:8000/auth/convert-token
And we done here from backend I hope you learned something from this.
Checkout my : part 2