Implementing Google OAuth in React.js

I'm going to explain How to implement the Google OAuth with React. In my previous article, I explained, How to create a new project in Google API Console create OAuth 2.0 Credentials and Configure the OAuth Client ID step by step.

Here I can share my previous article Understanding Google OAuth (Open Authorization)

I'm going to continue with my previous

What is Google Oauth?

Google OAuth leverages the OAuth 2.0 protocol to grant secure access to your Google data for third-party applications. This eliminates the need to share your password with these apps. When you encounter a third-party app requiring your Google data, you'll be redirected to a secure Google authorization server. There, you can grant permission for the app to access specific information from your Google account. Google then provides the app with an access token, which it uses to interact with Google APIs on your behalf. This approach empowers you to control what data third-party apps can access and revoke permissions anytime through your Google account settings.

Now we are going to create a React application for logging.

Step 1. Create a New React.js Project.

If you haven't already, create a new React.js project using Create React App or any other method you prefer:

Now I’m going to create a new react project as google-Aouth-client.

New react

Picture 1. Open the terminal and type follow this command.

Create new app 01. npx create-react-app google-oauth-client.

Move to the client folder 02. cd google-oauth-client

Client folder

Picture 2. Open the terminal and type the ‘npm start’ command.

Npm start

Picture 3. See the view.

Now we have to implement Google Auth with React js. We are installing the required Packages.

Step 2. Install the Required Packages
 

Installing these packages

  1. @react-oauth/google: Google OAuth2 using the new Google Identity Services SDK
  2. Axios: Promise-based HTTP client for the browser and node.js
  3. Jwt-decode: JSON Web Token can be decoded.

npm install @react-oauth/google Axios jwt-decode.

JSON Web Token

Picture 4. npm install @react-oauth/google Axios jwt-decode

You can go to react and check package.json package is installed or not.

Npm install

Picture 5. Check the package list.

I'm going to create two pages 01. Login 02. Logout pages.

Logout pages

Picture 6. Pages are created.

I'm going to integrate the login.jsx and logout.jsx pages into the app.js file.

Go to the App.js page

import "./App.css";
import Login from "./google-OAuth/login";
import Logout from "./google-OAuth/logout";

function App() {
  return (
    <div className="App">
      <h1>Google Auth</h1>
      <div className="center">
        <Login />
      </div>
      <div className="center">
        <Logout />
      </div>
    </div>
  );
}

export default App;

Google Auth

Picture 7. Go to the terminal and run this command npm start. And see the view in the browser.

Now, I am Going to implement the Google OAuth,

Step 3. Set Up a Google Developer Account and OAuth Credentials

I have already done these steps in my previous article Understanding Google OAuth (Open Authorization) and will continue from this article.

If you have already created the project then go to the link otherwise you can make a project through my article step-by-step.

https://console.cloud.google.com/cloud-resource-manager

Resource manager

Picture 8. See the Cloud resource manager panel.

Click on the Navigation Menu.

Navigation Menu

Picture 9. Go to the APIs and services Click it and go to click Credentials.

 Credentials

 APIs

Picture 10. Click on the Download icon and get your OAuth client ID credentials in a JSON file.

Now we get the Credentials ID.

Get the API Key Click on the SHOW KEY button.

API Key

Picture 11. Open the API KEY popup window and copy the API KEY.

Step 4. Create the env file in the client

The .env file, "environment," is commonly used in React and Node.js applications to store configuration variables. These variables can include sensitive information like API keys, database connection strings, or any other configuration parameters specific to the environment where the application is running.

Let's create an Environment variable in Node js.

  1. Go to the dotenv npm page. Install the npm package for dotenv for your node js application.
  2. Create an env file in node-js. Do not create a js file. Name it .env.

Go to the Client project create the ‘.env’ file and add Client-Id and API-key

Example

  • REACT_APP_GOOGLE_CLIENT_ID=23747474755454-l00bbj245pfb858lke849j1cjiv3c8n2b734ae.apps.googleusercontent.com
  • REACT_APP_GOOGLE_API_KEY=AIzDdSdWdaSyBMPeM-5gf5gf5g5f4_VBUMlmXXHMED-xqg

GOOGLE_API

Picture 12. Add the client ID and API key.

Step 5. Create the Login Page

Now I will create the Login page and refer to the @react-oauth/google npm package.

import React from 'react'
import {
  GoogleOAuthProvider,
  GoogleLogin,
  googleLogout,
} from "@react-oauth/google";
import { jwtDecode } from "jwt-decode";

const CLIENT_ID = process.env.REACT_APP_GOOGLE_CLIENT_ID;

export default function login() {

  const handelLogin=(googleData)=>{
    const userData = jwtDecode(googleData);
    console.log(userData);
  }

  return (
    <div className="App">
        <GoogleOAuthProvider clientId={CLIENT_ID}>
          <GoogleLogin
            onSuccess={(credentialResponse) => {
              handelLogin(credentialResponse.credential);
            }}
            onError={() => {
            }}
          />
        </GoogleOAuthProvider>
    </div>
  )
}
  • <GoogleOAuthProvider clientId={CLIENT_ID}>: This component named GoogleOAuthProvider is used for handling Google OAuth authentication. It likely takes a prop clientId, the client ID needed for authentication.
  <GoogleOAuthProvider clientId={CLIENT_ID}>
          <GoogleLogin
            onSuccess={(credentialResponse) => {
              handelLogin(credentialResponse.credential);
            }}
            onError={() => {
            }}
          />
        </GoogleOAuthProvider>
  • <GoogleLogin>: This is another component, possibly provided by the GoogleOAuthProvider, used to handle the login process with Google. It likely has event handlers like onSuccess and onError that are called when the login is successful or encounters an error.
  • jwtDecode: A function from the jwt-decode library that decodes JSON Web Tokens (JWT).
 const handelLogin=(googleData)=>{
    const userData = jwtDecode(googleData);
    console.log(userData);
  }

onSuccess has a function called handleLogin which passes the value from Google-Data and decodes the Google-Date using jwtDecode.

Now I'm going to run my app.

Run my map

Picture 13. Now you can see our page is running.

Click on the Sign in with Google button.

Google button

Picture 14. Login with gmail.

Get the console output by userData here.

Console output

Picture 15. Get the login information here.

We get the Google token from the Google login.

Conclusion

In this article, we've walked through the process of implementing Google OAuth in a React.js application. By leveraging the OAuth 2.0 protocol, we've ensured a secure method for third-party applications to access user data without compromising user credentials. We started by setting up a new React.js project and installing essential packages. Then, we configured OAuth credentials, created login and logout pages, and integrated Google OAuth using Google Identity. By following these steps, you can provide your users with a smooth and secure login experience. For more detailed information, refer to my previous article on Understanding Google OAuth. With this knowledge.


Orfium Sri Lanka
Globally based Software Developing & Data Processing Company