Google OAuth2 using the new Google Identity Services SDK for React using Jwt-decode

oloriasabi

Olorì Àṣàbí

Posted on June 27, 2022

Google OAuth2 using the new Google Identity Services SDK for React using Jwt-decode

In this tutorial, we will be learning how to make sign-ups stress free and hassle-free by implementing authentication via Google OAuth2 using the new Google Identity Services SDK for React @react-oauth/google🚀.

You'll need

  • To create-react-app React application that makes requests of your API 
  • Installation of jwt-decode 
  • Basic knowledge of React
  • Node.js installed
  • Code editor ( Visual Studio Code preferably )

Setting up Your Google Cloud project

To integrate Google Login into our React app, you need a Google Client ID. First, you'll need to create a Google Cloud project.
 

  1. Create a project and choose a name for your project.

Image description

  1. Once you have a project in place, proceed to Credentials - Create credentials - OAuth client ID.

Image description

  1. You'll need to configure your OAuth consent screen. Choose external since we want to give access to everyone with a Google account. Google will then ask for the app's name plus some developer contact details.

Image description

  1. Fill up the app registration form. For the most part, you can leave it blank.

Image description
Choose the scope best suited for the app that you shall develop and fill all other necessary inputs according your application requirement.

We head back to Credentials - Create credentials - OAuth client ID. Choose the Web application type and we can provide all Authorised origins and redirect URL' s.

Image description
We will see our Google client ID and a client secret. We'll only need the client ID.

Let's create our React App and Login Component

Once you have your Google Client ID, we start creating our React application to integrate Google Login.

We will start with create-react-app application, and add all necessary dependencies which are Google OAuth2 using the new Google Identity Services SDK for React @react-oauth/google🚀 and jwt-decode is a small browser library that helps decoding JWTs token which are Base64Url encoded.

Let's get started by running the following commands but make sure you have the necessary requirements for authenticating Google Login in React

  • Node.js installed
  • Code editor ( Visual Studio Code preferably )
  • Google Client ID
  • Basic knowledge of React

npx create-react-app google-login
cd google-login
npm install @react-oauth/google jwt-decode react-router-dom

Create a file named src/lib/GoogleLoginPage.js, with the following content:

import React from 'react';
import { FcGoogle } from 'react-icons/fc';
import { GoogleOAuthProvider } from '@react-oauth/google';
import { GoogleLogin } from '@react-oauth/google';

const GoogleLoginPage = () => {
  const responseGoogle = (response) => {
    console.log(response);
  }

  return (
    <div className="">
          <div className="">
            <GoogleOAuthProvider 
                clientId={`${process.env.REACT_APP_GOOGLE_API_TOKEN}`}
                >
             <GoogleLogin
              render={(renderProps) => (
                <button
                  type="button"
                  className=""
                  onClick={renderProps.onClick}
                  disabled={renderProps.disabled}
                >
                  <FcGoogle className="" /> Sign in with google
                </button>
              )}
              onSuccess={responseGoogle}
              onFailure={responseGoogle}
              cookiePolicy="single_host_origin"
            />
            </GoogleOAuthProvider>
          </div>
    </div>
  )
}

export default GoogleLoginPage
Enter fullscreen mode Exit fullscreen mode

You can run npm start and check your console to receive your encoded token which we will decode using jwt-decode.

Decoding Google Token using JWT-DECODE

Now that we have gotten our google response token, lets decode to get all necessary user info.

Still in the GoogleLoginPage.js let's update it

import React from 'react';
import { useNavigate } from 'react-router-dom';
import { FcGoogle } from 'react-icons/fc';
import { GoogleOAuthProvider } from '@react-oauth/google';
import { GoogleLogin } from '@react-oauth/google';
import { client } from '../client';
import jwt_decode from "jwt-decode";

const GoogleLoginPage = () => {
  const navigate = useNavigate();

  const responseGoogle = (response) => {
   //console.log(response);
    const userObject = jwt_decode(response.credential);
    //console.log(userObject);
    localStorage.setItem('user', JSON.stringify(userObject));
    const { name, sub, picture } = userObject;
    const doc = {
      _id: sub,
      _type: 'user',
      userName: name,
      image: picture,
    };
    client.createIfNotExists(doc).then(() => {
      navigate('/', { replace: true });
    });

  }

  return (
    <div className="">
          <div className="">
            <GoogleOAuthProvider 
                clientId={`${process.env.REACT_APP_GOOGLE_API_TOKEN}`}
                >
             <GoogleLogin
              render={(renderProps) => (
                <button
                  type="button"
                  className=""
                  onClick={renderProps.onClick}
                  disabled={renderProps.disabled}
                >
                  <FcGoogle className="" /> Sign in with google
                </button>
              )}
              onSuccess={responseGoogle}
              onFailure={responseGoogle}
              cookiePolicy="single_host_origin"
            />
            </GoogleOAuthProvider>
          </div>
    </div>
  )
}

export default GoogleLoginPage
Enter fullscreen mode Exit fullscreen mode

Let's do a break down of what we just did.

After getting our Google Login response in our responseGoogle() , we created a variable to store the decoded token by importing jwt-decode package and calling the response we got from our google login.

Now that the token has been decoded, we can now get our user info, store it into our localStorage, de-structure the necessary needed info and send it to the database.

Reconfigure Google OAuth

Lastly don't forget to configure all necessary Authorised JavaScript origins and Authorised redirect URIs in your Google API.

Hurray!!! we can now view, enjoy and test our finished application

Image description

You can check out the live demo here

You can view and download our source code at

Conclusion

In this tutorial, we have learnt how to Authenticate User with the Google OAuth2 using the new Google Identity Services SDK for React @react-oauth/google🚀 and decoding token with JWT-DECODE.
 
I really hope you learnt something new today, don't forget to like, share and comment. 

References

Google OAuth2 using the new Google Identity Services SDK for React @react-oauth/google🚀

Decoding JWTs token which are Base64Url encoded.

💖 💪 🙅 🚩
oloriasabi
Olorì Àṣàbí

Posted on June 27, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related