How to implement Google Login using Angular 17 with a standalone component


In this blog,  You’ll learn how to configure Google OAuth, set up the angularx-social-login package, and build a simple Google login functionality within a modern, Angular 17 app structure.

Prerequisites

Before we dive into the code, ensure that:

  • You have Angular 17 installed. If not, you can create a new Angular 17 project by running:
    ng new google-login-app --strict
    
  • Basic understanding of OAuth 2.0, JWT tokens, and Angular 17 features.
  • A Google Developer Console account to set up OAuth credentials.

Step 1: Set Up OAuth 2.0 Credentials in Google Developer Console

To integrate Google login into your application, you first need to create OAuth 2.0 credentials in the Google Developer Console.

  1. Go to the Google Developer Console:
    Visit Google Developer Console.
  2. Create a new project:
    Create a new project by clicking Select a Project and then New Project.
  3. Enable the Google Identity Services API:
    • In the sidebar, navigate to APIs & Services > Library.
    • Search for Google Identity Services and enable the API.
  4. Create OAuth 2.0 credentials:
    • In APIs & Services > Credentials, click Create Credentials, then select OAuth 2.0 Client IDs.
    • Choose Web application as the application type.
    • Under Authorized JavaScript origins, add your local development URL, typically http://localhost:4200.
    • Under Authorized redirect URIs, add the URL where your app will handle OAuth redirection (usually http://localhost:4200).
    • Save the Client ID and Client Secret for later use.

Step 2: Install Required Package for Google Login

We will use the @abacritt/angularx-social-login package to integrate Google login functionality into our Angular 17 application.

Run the following command to install the package:

npm install @abacritt/angularx-social-login

Step 3: Set Up Standalone Component for Google Login

Let’s create a standalone component that will handle Google login functionality.

3.1 Create the Standalone Component

Create a new file app.component.ts:

import { Component, OnInit } from '@angular/core';
import { SocialAuthService, SocialUser, GoogleLoginProvider } from '@abacritt/angularx-social-login';

@Component({
  selector: 'app-root',
  standalone: true,
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  user: SocialUser | null = null;

  constructor(private authService: SocialAuthService) {}

  ngOnInit() {
    // Subscribe to auth state to manage user login
    this.authService.authState.subscribe((user) => {
      this.user = user;
      console.log(user);
    });
  }

  signInWithGoogle(): void {
    // Trigger the Google login process
    this.authService.signIn(GoogleLoginProvider.PROVIDER_ID);
  }

  signOut(): void {
    // Log the user out of the app
    this.authService.signOut();
  }
}

In the above code:

  • We define a standalone component by setting standalone: true in the @Component decorator.
  • The component uses SocialAuthService to manage user login state and GoogleLoginProvider for handling Google login.
  • signInWithGoogle() triggers the Google OAuth flow, while signOut() logs the user out.

3.2 Set Up the Social Auth Service

Now we need to configure the SocialAuthService in main.ts (or the entry point of your app).

In main.ts, configure the Google login provider with your Google Client ID:

import { createApp } from 'angular';
import { AppComponent } from './app.component';
import { SocialAuthServiceConfig, GoogleLoginProvider } from '@abacritt/angularx-social-login';

createApp(AppComponent)
  .provider(SocialAuthServiceConfig, {
    autoLogin: false,
    providers: [
      {
        id: GoogleLoginProvider.PROVIDER_ID,
        provider: new GoogleLoginProvider('YOUR_GOOGLE_CLIENT_ID'), // Replace with your Google Client ID
      },
    ],
  })
  .mount('#app');

Step 4: Create the HTML Template

Next, let’s build a simple template (app.component.html) for the Google login button and displaying the user’s profile information after a successful login.

<div *ngIf="!user">
  <button (click)="signInWithGoogle()">Sign in with Google</button>
</div>

<div *ngIf="user">
  <h3>Welcome, {{ user.name }}</h3>
  <img [src]="user.photoUrl" alt="User Photo" />
  <p>Email: {{ user.email }}</p>
  <button (click)="signOut()">Sign out</button>
</div>

In this template:

  • If the user is not logged in, the Google login button will be shown.
  • Once logged in, the user’s name, email, and profile picture will be displayed, along with a Sign Out button.

Step 5: Run the Application

With everything configured, you can now run your Angular 17 application:

ng serve

Visit http://localhost:4200 in your browser. You should see the Sign in with Google button. Once clicked, the user will be redirected to Google for authentication, and after a successful login, you will see their profile details.

Step 6: Optional – Handling Authentication Tokens

After a successful login, the SocialUser object contains a variety of information about the user, including authentication tokens like idToken and authToken. You can send these tokens to your backend server for additional user authentication or to issue your own JWT tokens.

For example, you can send the token to your backend for verification:

const token = this.user?.idToken;
this.authService.verifyTokenWithBackend(token);

Conclusion

By leveraging Angular 17’s standalone components and the angularx-social-login package, you’ve successfully integrated Google Login into your Angular app. This approach simplifies your codebase, removing the need for an app.module.ts file while still providing seamless authentication for your users.

Whether you’re working on a small personal project or a large-scale application, social logins like Google are essential in today’s web development landscape, and Angular 17 makes it easier than ever to implement them.

Don’t forget to explore other authentication providers like Facebook or Twitter if you need a broader social login integration.

Happy coding with Angular 17, and enjoy building your next awesome app!