Build Angular Google OAuth2 Login Using the angular-oauth2-oidc Library in Browser Using TypeScript

 

Integrating Google OAuth2 login in an Angular application enhances user experience by enabling seamless, secure authentication. In this guide, we’ll walk through the process of implementing Google OAuth2 Login using the Angular OAuth2 OIDC library.

 


Prerequisites

 

Before we start, ensure you have the following:

  • Node.js and npm installed
  • Angular CLI installed (npm install -g @angular/cli)
  • A basic Angular application setup
  • A Google Cloud account to create OAuth credentials

 


Step 1: Setting Up Google OAuth Credentials

 

  1. Visit Google Cloud Console: Go to Google Cloud Console.

 

  1. Create a New Project:
    • Navigate to the “Project Selector” menu.
    • Click New Project and provide a project name.

 

  1. Enable APIs and Services:
    • Go to “APIs & Services” > “Library”.
    • Search for Google People API and enable it.

 

  1. Create OAuth Credentials:
    • Navigate to “APIs & Services” > “Credentials”.
    • Click Create Credentials > OAuth 2.0 Client ID.
    • Select “Web application” as the application type.
    • Add your redirect URI (http://localhost:4200 for development).

 

 

  1. Copy Client ID and Secret:
    • Save your Client ID and Client Secret for later use.

 

Step 2: Install Angular OAuth2 OIDC Library’

 

Install the required library in your Angular project:

 

 

Directory Structure of App

 

 

Step 3: Configure the OAuth2 Module

 

In your Angular project, configure the OAuth2 library to use Google as the identity provider.

 

  1. Import Required Modules: Update the AppModule to include the OAuth2 configuration in app.module.ts file

 

 

Set Up the Configuration in a Service: Create an auth-config.ts to manage OAuth settings.

 

 

Step 4: Initialize Authentication

 

  1. Modify AppComponent: Update the AppComponent to initialize the authentication process.

 

 

The typescript code for the above component is as shown below. First of all make the auth.service.ts file as well and copy paste the below code

 

auth.service.ts

 

 

Now we can import this auth.service.ts file in the typescript code for the component as shown below

 

 

Step 5: Test the Application

 

  1. Run the Application: Start the development server:

 

 

  • Access the Application: Open your browser and navigate to http://localhost:4200.
  • Authenticate with Google:
    • Click the Login with Google button.
    • Sign in with your Google credentials.
    • The application should display your name and email address after a successful login.
  • Logout: Test the logout functionality to ensure it clears the session.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *