Add Google Login to your React Apps in 10 mins
Tags: react, security, webdev, googlecloud
Published: 2020-06-27 12:49:34

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/u3e0jxnva6te9a3kx5ji.png)

As a client developer, Creating apps with authentication might be a tedious process. As we need to handle authentication in the server and maintain the code. It does have some multiple cases to be maintained based on authentication mechanisms. (Basic, OAuth, etc) This blog helps you create a standalone backend less authentication for your react app. (or additionally) you can add server configurations too to authenticate with your server.

## Why OAuth?

There are many reasons to use OAuth. 

- It is secure.
- It doesn't require any credentials from the user. So no need of remembering multiple passwords.
- Websites can also get essential information about users without spending much time in forms.

And specifically in our case, we don't need a server to authenticate or to get initial details of the user. 😉

I found a package which is called as `react-google-login`. Which provides simple mechanisms to add the Google login. You can either directly use their `GoogleLogin` component or you can use custom buttons. They also provide custom hooks like  `useGoogleLogin` and `useGoogleLogout` so it will be easy for hooks lovers. *(Both methods are described below)* 

The [documentation](npmjs.com/package/react-google-login) they provided for this repository is awesome. But it's missing in some ways which are addressed in this blog. Like in detail, this blog helps in creating your application in the Google developer console and access `clientId`.  The initial `access_token` obtained by this package will last for only one hour (*For security reasons).* And we need to iterate the process to access the new `access_token` using `refresh_token`. So you can make a **production-ready application.**

## Steps

- We need to create an application in the Google developer console. It provides `clientId` is used to identify your application for authentication details. Follow the below steps to get the client ID.
    1. Go to the [Credentials page](https://console.developers.google.com/apis/credentials). *( if you are new, then [create a project](https://console.developers.google.com/projectcreate) and follow these steps)*
    2. Click **Create credentials > OAuth client ID**.
    3. Select the **Web application** type.
    4. Name your OAuth 2.0 client and click **Create**
- Make sure you provided your domain and redirect URL. So that Google identifies the origin domain to which it can provide authentication.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/hhihbf8d3k4pvul9br19.png)

You can also add your local route for development. Now authentication setup in Google developer console is ready.

## Lets code

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/yj64on55mqjghaszl1ot.png)

Let's start with code. [View my repo](https://github.com/sivanesh-s/react-google-authentication/) for accessing all code snippets. View [Demo](https://sivanesh-s.github.io/react-google-authentication/).

In your CRA install `react-google-login` package

```powershell
npm i react-google-login
```

Create a `Login` component that acts as a login button.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/w9aw8o6ef8cbmrla9o4g.png)

Similarly, create a `Logout` component

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/83ty6je2wy3anjyb0jed.png)

And add both in the required location of your app. Mine is in `App.js`

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/b3do0if6wxwj5nhmy7l8.png)

Now running your application will show `profileObj` in the console after logging in.

Congrats 🎉 You successfully made it 😃.

 But after 1 hour your `tokenId` gets expired and hence it won't be used to access data or authenticate users. And hence we need to generate new `tokenId`. To make things work we need to add some additional cases in the `Login` component.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/iphh0mab7jmr7y9pv0na.png)

`refreshTokenSetup` function will take care of handling new `tokenIds`

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/fgw32rcpf6piy6q42kbc.png)

This function checks for `expires_in` timestamp or our custom time *(before the token expires)* and calls `reloadAuthResponse` which is a util function provided by the library and it handles `refresh_token` and obtains new `tokenId`. 

 

And Yeah 😃 Google login is added to your application successfully 🎉. So now you can access the user's **name, photo URL, email, google Id,** etc. 

## Additional

The above way uses the Google Login default button. You can also use your custom button using `render` prop.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/rbh2gg48dschpmaugg5d.png)

We can also implement the same functionality using **React Hooks.** ❤️

`LoginHooks.js`

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/xgx3ires7pcywocdqyxu.png)

`LogoutHooks.js`

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/e0apz4pgs42ssw4t41ky.png)

## Server-side verification

If you wish to add Server side verification, Send the `tokenId` from client to server once `onSuccess` in `Login` component called.

So while handling authenticated routes, All requests from the client need to send the `tokenId` of the user in the header as **Bearer token.** At Server, once token received it must be verified either this `tokenId` 

- belongs to the current application.
- Has it expired

You can do them manually but google suggests using their authentication library *(Minimal effort required)*. 

In the Server side *(Here Node.js is used).* 

Install Google's official supported library `google-auth-library` package which is used to authenticate and verify OAuth apps.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/0l6r82sapc8jbyzfg1ch.png)

Here, With our `GOOGLE_CLIENT_ID` sent it verifies whether this token belongs to our application or not. And it parses them and provides profile details in the `getPayload` function. And you can use them to access user data.

Any queries feel free to comment or chat with me personally in my social media accounts below. 

I love to be connected with developers. 😃 

[Twitter](https://twitter.com/sivanesh_fiz) | [LinkedIn](https://www.linkedin.com/in/sivanesh-shanmugam/) | [GitHub](https://github.com/Sivanesh-S)