Google SSO User Validation NodeJS

Lijoy C George
3 min readApr 8, 2021

How to integrate Google SSO to your ReactJS application. And validate them and save details to your DB through your NodeJS express API.

Application Architecture ( IMG 1 )

React App

In react app we are using GoogleLogin plugin to integrate Google SSO.

Installation

npm install GoogleLogin --save

Usage

import { GoogleLogin } from “react-google-login”;

Import the package in your component like login.component.tsx.

HTML Snippet

Use the below snippet in your component.

const CLIENT_ID = 'Your_Google_API_client_ID';...
<GoogleLogin
clientId={CLIENT_ID}render={renderProps => (<button className=”signup-btn” onClick={()=>{renderProps.onClick()}} disabled={renderProps.disabled}><img src=”images/Image 4.png” alt=”” /><span className=”signup-label”>Sign in with Google</span>{/* <Loader type=”ThreeDots” color=”#255D4F” height={10} width={50} visible={googleLoaderIsVisible}/> */}</button>
onSuccess={(res)=>{googleLogin(res)}}
onFailure={(error)=>{googleLoginFailed(error)}}cookiePolicy={‘single_host_origin’}/>

onSuccess

googleLogin funtion will be triggered on success full SSO login.

This will make an API call using axios or fetch to verify / create user. Read Verify Token section.

const googleLogin = (data:any)=>{// Show loaderssoLogin({‘token’:data.tokenObj.id_token}). // API call to invoke NodeJS verify functionthen((response)=>{// Hide Loaderif(response.data.status == 200){setToken(response.data.data.accessToken).then(() => {// Navigate to dshboard})} else {// Handle error}}).catch((error) => {// Handle error})}

onFailure

When SSO login fails this function will be triggered. We can handle error conditions here.

const googleLoginFailed = (error:any)=>{// hide Loaderif(error.error !== “popup_closed_by_user”){alert(error.error);}}

cookiePolicy

The domains for which to create sign-in cookies. Either a URI, single_host_origin, or none. Defaults to single_host_origin if unspecified.

Other Parameters

scope

The scopes to request, as a space-delimited string. Optional if fetch_basic_profile is not set to false.fetch_basic_profilebooleanFetch users' basic profile information when they sign in. Adds 'profile', 'email' and 'openid' to the requested scopes. True if unspecified.

hosted_domain

The G Suite domain to which users must belong to sign in. This is susceptible to modification by clients, so be sure to verify the hosted domain property of the returned user. Use GoogleUser.getHostedDomain() on the client, and the hd claim in the ID Token on the server to verify the domain is what you expected.You must request the 'email' scope when using this parameter alongside fetch_basic_profile: false.

ux_mode

The UX mode to use for the sign-in flow. By default, it will open the consent flow in a popup. Valid values are popup and redirect.

redirect_uri

If using ux_mode='redirect', this parameter allows you to override the default redirect_uri that will be used at the end of the consent flow. The default redirect_uri is the current URL stripped of query parameters and hash fragment.

NodeJS App

In our NodeJS Application we are using google-auth-library plugin to verify SSO id token.

Installation

npm install google-auth-library — save

Usage

Import the module in your handler/controller

const { OAuth2Client } = require(‘google-auth-library’);

Verify Token

const CLIENT_ID = 'Your_Google_API_client_ID';const verify = async (token) => {const client = new OAuth2Client(CLIENT_ID);return new Promise(async (resolve, reject) => {const ticket = await client.verifyIdToken({idToken: token,audience: CLIENT_ID}).catch((error) => {reject(error)})if (ticket) {const payload = ticket.getPayload();const userid = payload[‘sub’];resolve(payload)}})}

CLIENT_ID

To enable Sign In With Google on your website, you first need to set up your Google API client ID.

How To Get CLIENT_ID

  1. Open the Credentials page of the Google APIs console.
  2. Create or select a Google APIs project. If you already have a project for the Sign In With Google button or Google One Tap, use the existing project and the web client ID.
  3. If your project doesn’t have a Web application-type client ID, click Create credentials > OAuth client ID to create one. Be sure to include your site’s domain in the Authorized JavaScript origins box. Please note that Google One Tap can only be displayed in HTTPS domains. When you perform local tests or development, you must add both http://localhost and http://localhost:<port_number> to the Authorized JavaScript origins box.

Note: CLIENT_ID used in NodeJS application and ReactJS application should be same.

--

--