Authenticate with Google in Angular 17 via OAuth2

Kushal Ghosh
5 min readNov 22, 2023

--

Given the continuously growing user base, there is a demand for an advanced authentication system that is both uncomplicated for developers to oversee and trustworthy for users, especially considering the heightened importance of personal data in today’s context.

OAuth2 (or Open Authentication 2.0) tries to mitigate this situation by providing a solution that allows your users to log in to web apps using their social media accounts. This means users can log in with existing profiles without ever compromising on security. It also saves the developers the cumbersome task of maintaining a separate authentication system.

There are multiple ways to achieve our goal of authenticating with Google and retrieving the authorized data of logged-in users (of course).

Multiple ways such as —

  1. Front-end-oriented implementation.
  2. Combination of Front-end logic and back-end server.

We’ll talk about all the available ways, but first thing first configuring the OAuth2 project in Google Console as it is common for all the ways available(definitely).

Note — Google Sign-in for Web library is deprecated and now the latest way of implementing the sign-in with Google has been introduced which we are using here.

In this project we are implementing Front-end oriented implementation only.

Setup and Configure

Head over to Google Developer Console, follow the below steps

Step 1 — Create a Project and head over to API and Services.

Step 2 — Go to Credentials and configure the Oauth Consent screen. If you are doing it locally then there is no need to provide an App domain and Authorized Domain(optional)

Step 3 — Under Scopes Add below scope for retrieving user’s public profile info.

Select the fields(scopes) which have user info
Select the fields(scopes) which have user info

Step 4 — After configuring the consent screen head back to Credentials and click on Add Credentials.

Step 5 — Under Create Credentials choose Oauth Client ID and change Application type to Web.

Add the Authorized URLs(for this instance localhost is the domain)

Step 6 — Complete the steps and take the client ID with you.

Step 7 — Go to this Google Configurator website, generate code for your website(updated way), and paste your client ID.

Step 8 — Add the login URI(this is the endpoint where all the data will be pushed to when there is any backend server to handle the Google response)

Step 9 — Enable one-tap signing (if you want) and enable the signing button with Google to generate the HTML code.

Copy the generated HTML code which will be used further

Method 1: Implementing the OAuth2 in Angular 17

This technique talks about Front-end orientation implementation. Create a login component in angular, and follow the steps —

Step 1 — Add the Google’s Oauth library inside the head tag of the index.html


<script src="https://accounts.google.com/gsi/client" async></script>

Step 2 — Paste the generated HTML code into the login component’s HTML file, BOOM! Now you can see the Google sign-in button and one tap(if enabled).

Reference of successful authentication

Step 3 — Remove the ‘data-login_uri’ and add ‘data-callback’; this is the function in which we will handle the JWT response(token).

<div id="g_id_onload"
data-client_id="paste-your-cliend-id-here"
data-context="signin"
data-ux_mode="popup"
data-itp_support="true"
data-callback="handleOauthResponse"
>
</div>

<div class="g_id_signin"
data-type="standard"
data-shape="rectangular"
data-theme="outline"
data-text="signin_with"
data-size="large"
data-logo_alignment="left">
</div>
Refer to this official documentation

Step 4 — Add the handleOauthResponse function to handle the token and retrieve the user details.

  <!-- Function to handle the JWT response -->
<script>
function decodeJWTToken(token){
return JSON.parse(atob(token.split(".")[1]))
}
function handleOauthResponse(response){
const responsePayload = decodeJWTToken(response.credential)
console.log(responsePayload)
sessionStorage.setItem('loggedinUser',JSON.stringify(responsePayload))
window.location('/your-desired-place')
//Changed the above URL where you want user to be redirected
}
</script>

Note — We can emit a login event after a successful login to add more things, but I am simply adding a simple redirection.

You can use the loggedinUser session item to retrieve the personal detail or to implement any further logic.

This is not limited to only angular rather we can implement the same technique to any other tech stack.

Note — If you are using the ‘login_url’ technique then you need to have a backend server where the JWT token will be sent using a POST request and this token as a response should need to be handled on the server side only(this was front end oriented project).

Method 2: Implementing the OAuth2 in Angular 17

This technique talks about Front-end orientation implementation. Create a login component in angular, and follow the steps —

Step 1 — Add Google’s Oauth library inside the HTML file of the login component.

<script src="https://accounts.google.com/gsi/client" async></script>

Step 2 — Import the following in the app.config.ts

import { SocialAuthServiceConfig } from '@abacritt/angularx-social-login';
import {
GoogleLoginProvider,
} from '@abacritt/angularx-social-login';

Step 3 — Add the below code into the providers of app.config.ts

{
provide: 'SocialAuthServiceConfig',
useValue: {
autoLogin: false,
providers: [
{
id: GoogleLoginProvider.PROVIDER_ID,
provider: new GoogleLoginProvider(
'paste-your-google-client-id-here'
)
}
],
onError: (error) => {
console.error(error);
}
} as SocialAuthServiceConfig,

Step 4 — This will be the login component ts file

import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SocialAuthService, GoogleSigninButtonModule } from '@abacritt/angularx-social-login';

@Component({
selector: 'app-login',
standalone:true,
imports:[
CommonModule,
GoogleSigninButtonModule
],
templateUrl: './login.component.html',
styleUrl: './login.component.css'
})
export class LoginComponent implements OnInit{
constructor( private authService:SocialAuthService) {}

ngOnInit(): void {
this.authService.authState.subscribe((user) => {
console.log(user)
//perform further logics
});
}
}

Step 5 — Add the below code into the HTML file of the login component to render the Google Sign-in button

<asl-google-signin-button type='standard' size='medium'>
</asl-google-signin-button>

Note — This is updated for Angular 17+ versions.

HAPPY CODING! (pink heart, laughing emoji)

--

--