Login with Google in Web Application(React.js)

Prachi
3 min readAug 11, 2020
Photo by Daniel Leone on Unsplash

Introduction

Hello folks! Here we are going to integrate Google Login in our web app.Google is the identity provider here i.e we don’t have to verify the user’s email and profile.Google does that well for us. Get the full code here(with a sign out and showing logged user data in different pages): Github

There are 3 steps to follow:-

  1. Create authorization credentials(in short getting Client ID)
  2. Include google platform library in our web app that integrates google login.
  3. Add google login button and the functionalities.

Create authorization credentials

Go to Google’s developer’s site at: https://console.developers.google.com.

Go to Credentials >> Create Credentials >> Select OAuth client ID

Add JavaScript origins and Redirect URL

After pressing Create button you will get your client id.

Include google platform library

Create a react app and make 3 files:- Login.js, Home.js, Routes.js

Basic structure of Login.js

The basic structure of Home.js

Routes.js looks like

For loading the google platform library, we need to insert a script. Below is the code snippet for the loading platform library and after that loading auth2 library.

Go here for the reference to script-src.

insertScript()- In this function we have created theScript tag and after loading the platform library we have called the function initializeGoogleSignIn.

initializeGoogleSignIn()- This function is called for loading auth2 library.

So till now our app looks like

Now its time for rendering the Google Sign In button

I am redirected to google sign in modal

We pass two arguments to the render function in the above code snippet.

  1. The id of the button(here it is ‘loginButton’)
  2. params:- This is the object having properties like width, height, longTitle(It shows ‘Sign in with Google’ instead of just ‘Sign in’), and the most important one -onsuccess. It gets fired when the user clicks on Sign in(in the modal which google provides for entering email and password).

When the user signs in successfully, the console prints ‘User has finished sign in.

But what if we want to get the logged-in user details???

googleUser.getBasicProfile() has details like id, name, image URL and email. You can send the details of the user to ‘/home’ route and show the results there.

Also you get token by googleUser.getAuthResponse().id_token you can send this token to back-end and decrypt it for user details.

See the details printed on console

In the next article, we will talk about sending the token to the back-end and getting out data of the logged-in user.

Get the full code here(with a sign out and showing logged user data in different pages): Github

--

--