DEV Community

Aditya
Aditya

Posted on

ReactJS + NodeJS Google Auth Login Implementation on Webapps

With the building of web-applications, there comes a need to have a OAuth Login implementation in any project. There are a number of providers through which we can login to applications such as Google, Facebook, Twitter, Github and many more.

Google Login

Thus an implementation for the web developers is important on how to achieve the login functionality in their web-apps using these providers.

WE went through the same journey and would guide you through the process on how to achieve the Google Login functionality on your web-application.

Pre-requisite
We expect you to have background in the NodeJS and ReactJS development and how to serve a complete web-app using both.

React Setup
We would be using the standard npm library for performing the Google Login on Frontend.

react-google-login

Steps to install

  1. For npm, npm install react-google-login
  2. For yarn, yarn add react-google-login

Once installed, you are ready to create your login screen.
Use the snippet below for your Login screen.

import React from 'react'
import { GoogleLogin } from 'react-google-login';
import { makeStyles } from '@material-ui/core/styles';
import { useHistory } from 'react-router-dom';

const useStyles = makeStyles((theme) => ({
    button: {
        margin: theme.spacing(1),
    },
}));

export default function Login() {

    const classes = useStyles();
    const history = useHistory()

    const onGoogleSuccess = (response) => {
        const access_token = response.tokenId;
        fetch(
            '/googleLogin', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ tokenId: access_token })
        }
        ).then((res) => {
            if (res.status === 200) {
                history.push('/')
            } else {
                history.push('login')
            }
        }).catch((err) => {
            throw new Error(err);
        })
    }

    const onGoogleFailure = (err) => {
        console.log(err)
    };

    return (
        <div
            style={{
                width: "100%",
                height: "100vh",
                display: "flex",
                flexDirection: "column",
                justifyContent: "center",
                alignItems: "center",
                backgroundColor: "#151a30",
                color: "white",
            }}
        >
            <h1>Google Oauth Sign In</h1>
            <GoogleLogin
                clientId={process.env.REACT_APP_GOOGLE_CLIENT_ID}
                buttonText="Sign in with Google"
                onSuccess={onGoogleSuccess}
                onFailure={onGoogleFailure}
                className="google-login-button"
                cookiePolicy={'single_host_origin'}
            />
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

The npm library google-auth-library comes with a two functions, onSuccess and onFailure.

To know more about the library and it's various implementations: NPM react-google-login

Once the successful login is approved by the Google Servers, we get a response containing the tokenId, we use the tokenId and send it to our server where our server will connect to google servers to fetch the profile info of the logged-in user.

Node Setup
We create a standard server with a route exposed at /googleLogin as shown in the React onSuccess fetch call.

That will route the call to a controller we will create below.

We would be using Google's standard library to perform the OAuth from server side, google-auth-library.

To know more about the library, please refer to the links below

  1. NPM Docs
  2. Google Docs

Server controller snippet

const { OAuth2Client } = require('google-auth-library');
const controller = require('./controller');

const client = new OAuth2Client(process.env.GOOGLE_DEFAULT_CLIENT_ID);

const clientId = process.env.GOOGLE_DEFAULT_CLIENT_ID;

exports.googleLogin = (req, res) => {
    var inputJSON = JSON.stringify(req.body);
    var parsedJSON = JSON.parse(inputJSON);
    const { tokenId } = parsedJSON;
    var verifyObject = {};
    verifyObject.idToken = tokenId;
    verifyObject.audience = clientId;
    client.verifyIdToken(verifyObject)
        .then(response => {
            const { email_verified } = response.payload;
            if (email_verified) {
                controller.addUser(req, res, response.payload);
            } else {
                res.json({ status: 403, message: 'Email Not Verified, use another method to login!' });
            }
        });
};
Enter fullscreen mode Exit fullscreen mode

The controller uses a verifyIdToken function which checks for the token sent from React UI and in case of a successful checks returns an object which contains profile data of the user.

Common Fields we get in response

  1. name
  2. issuer
  3. profile_picture
  4. email
  5. verified_email: True|False and so on....

Once we have that info, we can use that info as per our use case, in our case we proceeded to add the data to our backend database.

This was a small writeup on how to perform the full Integration of Google Auth Login using ReactJS and NodeJS.

Top comments (0)