Google Authentication

Introduction:

Google Authentication is a popular choice for adding secure and convenient login functionality to web applications. In this blog post, we'll walk through the steps to integrate Google Authentication into a ReactJS application.

Create a react app and add these dependencies.

1pnpm create vite@latest my-react-app

Lets add google authentication to our app.

add the following line to the site index.html

html:index.html
1<html>
2...
3 <head>
4 ...
5 <script src="https://accounts.google.com/gsi/client" async defer></script>
6 ...
7 </head>
8 <body>
9 ...
10 </body>
11</html>

Lets create a GoogleLoginButton component to display the google login button.

tsx:arrow/index.tsx
1import { useCallback, useEffect, useRef } from 'react';
2import { useLocation } from 'react-router-dom';
3
4const GOOGLE_CLIENT_ID = import.meta.env.VITE_APP_GOOGLE_CLIENT_ID; //<-- your google client Id
5
6export function GoogleLoginButton() {
7
8 useEffect(() => {
9 const google = window.google;
10 if (google && google.accounts) {
11 google.accounts.id.initialize({
12 client_id: GOOGLE_CLIENT_ID,
13 callback: (response: any) => {
14 console.log(response.credential);
15 },
16 });
17
18 google.accounts.id.renderButton(document.getElementById('signInDiv'), {
19 theme: 'outline',
20 size: 'large',
21 });
22 }
23 }, []);
24
25 return <div id='signInDiv'></div>;
26}
27

This will render a button like this.

Google Signin

Upon clicking the button will launch the window with 0-n google accounts that you are signed in

Google Accounts

Clicking Use another account will take you thru the google signin/signup process.

Upon selecting the signed in account, the callback' handler will be called with the user id token` as credentials.

1{
2 "credential": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImJkYz ... -z_XyCsu_Wtm9r-8n4YLe2uyNw"
3}

Serverside Validation of tokens

This credentials may be passed on to your .NET server to exchange for access tokens.

Your .net can use the app client id to validate the token

1public async Task<User> SignInAsync(string credential) {
2 var payload = await GoogleJsonWebSignature.ValidateAsync(credential, new GoogleJsonWebSignature.ValidationSettings
3 {
4 Audience = new[] { GOOGLE_CLIENT_ID }
5 });
6
7 return payload ?? new User
8 {
9 Email = payload.Email,
10 FirstName = payload.GivenName,
11 LastName = payload.FamilyName,
12 };
13}

Conclusion

Integrating Google Authentication in a ReactJS application is a straightforward process. By following these steps, you can provide users with a seamless and secure login experience using their Google accounts.