DEV Community

elite_developer
elite_developer

Posted on

Integrate Google OAuth2 Social Authentication into your Django x React Web Application.

Requirements

  • A VS Code editor installed.

  • More than basic understanding of Django and React

  • A Custom or Pre built django user model already configured

set up virtual environment and pip install these packages


 -m venv .venv

# start virtual environment
.venv/scripts/activate # windows command

# then install
pip install django django-allauth
pip install django-allauth dj-rest-auth djangorestframework-simplejwt


Enter fullscreen mode Exit fullscreen mode

Now we Build
Inside your root directory, create a Django project like this:
startproject core .

Django will create a new directory called

core
in the current working directory.

Next, create an application called

authentication
:

py manage.py startapp authentication

The above command invocation will create an app directory called authentication at the same level as your project directory core. Proceed to include your new application in the list of INSTALLED_APPS section of the newly created settings.py file:

# core/settings.py
INSTALLED_APPS =  [
    ...
    'authentication',
    ...
]


Enter fullscreen mode Exit fullscreen mode

2. Django Configuration (settings.py)
Add the required apps and configure the authentication backends.

INSTALLED_APPS = [
    # ... standard apps
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',
    'rest_framework',
    'rest_framework.authtoken',
    'dj_rest_auth',
    'dj_rest_auth.registration',
]

SITE_ID = 1

REST_AUTH = {
    'USE_JWT': True, # Use JWT for modern React SPA authentication
}

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'allauth.account.auth_backends.AuthenticationBackend',
]

# Google settings
SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE': ['profile', 'email'],
        'AUTH_PARAMS': {'access_type': 'online'},
    }
}
Enter fullscreen mode Exit fullscreen mode

Set up an App in Google Developer Console

Set up an App in Google Developer Console
You need to set up an app in Google Console to enable users of your application authenticate with Google. The process involves two steps:

Configuring an OAuth consent screen

  • Setting up Credentials

  • OAuth consent screen

  • Visit Google developer console.

  • Create a new project with a suitable name from the dropdown menu.

Image Image showing google dev console

Select to use the project you have just created from the dropdown menu.
In the displayed window, select OAuth consent screen and select the External option, then hit Create.Google developer console OAuth2 consent screen
Fill in only the App information and Developer information details under Oauth2 consent screen.

  • Click on Save and continue.
  • Click on Save and continue button for both Scopes and Test users forms without filling in anything.

  • Confirm your Oauth2 details in the Summary section then click on Back to dashboard.

  • Set up Credentials

  • Locate Credentials under APIs and Services

Click on Create Credentials and select OAuth Client ID from the dropdown options.The credentials screen in Google developer console
Select Web application for the Application type field. You could use the default name under the Name field or provide a suitable name.
Select ADD URI under Authorized JavaScript Origins to add a Uniform Resource Identifier (URI).

Info: Adding a URI ensures only permitted domains can send requests to your OAuth2 app from a browser. Since you will be using your react app in development, add this local host URI:
http://localhost:5173/

Select ADD URI under Authorized Redirect URIs and add the following URI:
http://localhost:5173/dashboard

Info:This is the callback URL where Google will redirect to after a user grants or denies your application permission to authenticate with their Google account.

Hit the Create button and wait for a few seconds for your app to be ready. Your new app will generate a Client ID and Client secret. In the resulting window, download the JSON for these details or copy and paste the Client ID and Client secret somewhere. You will need these details in a few.

3. Setup the API Bridge (views.py)
This is where you define the bridge that links Google’s response to your Django user system. Create this in your app's views.py.

from dj_rest_auth.registration.views import SocialLoginView
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from allauth.socialaccount.providers.oauth2.client import OAuth2Client

class GoogleLogin(SocialLoginView):
    adapter_class = GoogleOAuth2Adapter
    # client_class is only needed if you are using specific OAuth2 flows
    client_class = OAuth2Client





Enter fullscreen mode Exit fullscreen mode

3. Define the URL (urls.py)

# urls.py
from django.urls import path
from .views import GoogleLogin

urlpatterns = [
    path('api/auth/google/', GoogleLogin.as_view(), name='google_login'),
]
Enter fullscreen mode Exit fullscreen mode

The Frontend (React)

1. npm install
npm install @react-oauth/google axios

2. Wrap your App
Wrap your main component so the Google SDK is available globally.

// index.js or App.js
import { GoogleOAuthProvider } from '@react-oauth/google';

export default function App() {
  return (
    <GoogleOAuthProvider clientId="YOUR_CLIENT_ID_FROM_GOOGLE_CLOUD.apps.googleusercontent.com">
      <Login />
    </GoogleOAuthProvider>
  );
}
Enter fullscreen mode Exit fullscreen mode

3. The Login Logic
Use the useGoogleLogin hook. It handles the pop-up and gives you the access_token to send to your Django API.

// Login.jsx
import { useGoogleLogin } from '@react-oauth/google';
import axios from 'axios';

export default function Login() {
  const googleLogin = useGoogleLogin({
    onSuccess: async (tokenResponse) => {
      try {
        // Send the token to your Django endpoint
        const response = await axios.post('http://localhost:8000/api/auth/google/', {
          access_token: tokenResponse.access_token,
        });

        // The response contains your JWTs
        console.log("Success:", response.data);
        localStorage.setItem('access_token', response.data.access_token);
      } catch (error) {
        console.error("Auth failed:", error);
      }
    },
    onError: (error) => console.log("Login Failed", error),
  });

  return <button onClick={() => googleLogin()}>Sign in with Google</button>;
}
Enter fullscreen mode Exit fullscreen mode

Final Step - Admin Setup

If you skip this, it will never work.

  • Run py manage.py makemigrations and py manage.py migrate.
  • Start your server and log in to /admin.
  • Go to Social Applications.
  • Click Add.

  • Provider: Google.

  • Client ID & Secret: Paste these from your Google Cloud Console.

  • Sites: Move example.com to the "Chosen" box.

  • Save.

Top comments (0)