How to Implement Sign-in with Google in Angular and a REST API

| By Maina Wycliffe | | | Angular

A few weeks ago, I demonstrated how to implement Sign in with Facebook with a REST API. Today, I will show you how to Sign-in with Google in Angular 5 with a REST API involved. We will use PHP at the backend, but this will work with any backend language you are totally comfortable with. To put it simply, your Angular App will request a token from Google OAuth Servers and then send the token to the REST API.

The REST API will then validate the token against Google Servers (Never Trust Anything from the User) and if genuine, Sign-in or create account or do something that needed user to be authenticated. You will also get user profile data from Google including the profile picture which you can store for future reference. Let’s get started:

Create a Google App and Get API Credentials

The first thing we need is to create Google Project, so that we can get Access Credentials. To do this, you can head over to Google Developer Console and create an account or login with an existing account.

How to Implement Sign-in with Google in Angular and a REST API

First, click on create project button near the top left corner and enter the name for your project and click save. Wait until the project has been created. Then, select the project you just created and go to the credentials of API and Services for the project by clicking on the menu icon on the top left corner, then select API and Services, and then Credentials.

If it’s a new project, you won’t have any credentials on your screen. There are a few things you need to do here. The first thing is to configure your OAuth Consent Screen. This is the screen users will see with your app name and logo as you ask for permission during the Sign in with Google Process. To configure the OAuth Consent Screen, click on the OAuth Consent Screen Tab (Refer to the image below) and fill in the requested details. The name of the App is mandatory.

How to Implement Sign-in with Google in Angular and a REST API

Next, you need to create OAuth Credentials for your project. You should see a Create Credentials button on the screen, either at the middle of the screen or on top of the Credentials tab, just beneath the toolbar of the window. Click on the Create Credential Button, and select OAuth Client Id option in the drop-down menu that follows. In the next page, select Web Application from the options under Application Type.

And then provide the name of the credentials and click Create button. You might want to restrict the authorized domain names in the restriction section before creating the credentials. Here you will get the Client Id and the Client Secret, store them securely as you will need them for the steps that will follow.

Add Sign-in with Google to your Angular Application

Assuming you have successfully created a project, let’s go on and add a Sign-in with Google button to your angular app. To achieve this, we will use angularx-social-login module. You can install it using NPM or Yarn:

npm install --save angular5-social-login

// Or use yarn
yarn add angularx-social-login

Then import the Angular Social Login module into your app module as show below:

import {
  SocialLoginModule,
  AuthServiceConfig,
  GoogleLoginProvider
} from 'angularx-social-login';

Then create a new file socialloginConfig.ts in the root of your project and add a config file for social login:

import {
  SocialLoginModule,
  AuthServiceConfig,
  GoogleLoginProvider
} from 'angularx-social-login';

export function getAuthServiceConfigs() {
  let config = new AuthServiceConfig([
    {
      id: GoogleLoginProvider.PROVIDER_ID,
      provider: new GoogleLoginProvider()<GoogleClientIdJHere>
    }
  ]);

  return config;
}

NB: Replace the GoogleClientIdHere with your client id from the Google Project you created in the first step. Then import getAuthServiceConfigs into your app modules:

import { getAuthServiceConfigs } from './socialloginConfig ';

And finally import SocialLoginModule and add providers for SocialLoginModule as show below

@NgModule({
  imports: [
      // ...
      SocialLoginModule
   ],
   providers: [
      // ...
      SocialLoginModule.initialize(getAuthServiceConfigs)
   ],
   bootstrap: [
      //...
   ]
})

Add to your Sign In Page

Then, on your sign in component, import the AuthService, GoogleLoginProvider as shown below:

import { AuthService, GoogleLoginProvider } from 'angular5-social-login';

And Inject AuthService into your component as shown below:

constructorprivate socialAuthServiceAuthService ) {}

Then, add a method to handle Sign-in with Google and a button to your component. The method will look like this:

public signinWithGoogle () {
   let socialPlatformProvider = GoogleLoginProvider.PROVIDER_ID;

   this.socialAuthService.signIn(socialPlatformProvider)
   .then((userData=> {
      //on success
      //this will return user data from google. What you need is a user token which you will send it to the server
      this.sendToRestApiMethod(userData.idToken);
   });
}

And then add a Sign in with Google button as shown below:

<button (click)="signinWithGoogle()">Sign in with Google</button>

The sendToRestApiMethod is a method that will use HTTP to post the data to your REST API. The Token Id (idToken)received from Google should be either a parameter or form data depending on the HTTP method you use to send the data to the server.

Here is an example:

sendToRestApiMethod(token: string) : void {
   this.http.post("url to google login in your rest api",
      {
         token: token
      }
   }).subscribe(
      onSuccess => {
         //login was successful
         //save the token that you got from your REST API in your preferred location i.e. as a Cookie or LocalStorage as you do with normal login
      }, onFail => {
         //login was unsuccessful
         //show an error message
      }
   );
}

Integrating with your REST API

My REST API will be using PHP, but you can use any language you are comfortable with. For further and detailed tutorials for other language am not covering, visit the official documentation from Google here. First, install PHP Google SDK using composer as shown below (For detailed installation instruction, visit this link):

composer require google/apiclient

Once the installation is complete, go to your login script or method and call the Google OAuth endpoint to verify the Token Id (idToken) and create an account or grant user access to server-side resources or something. First, initialize the Google SDK as shown below:

$client = new Google_Client([
   'client_id' => '<GOOGLE CLIENT ID HERE>'
]);

And then send the Token Id (idToken) to the server for verification as shown below:

$payload = $client->verifyIdToken($idToken);

Then, compare the claim aud value with your google client id to ensure that the idToken you got from your app was meant for your client and its valid. If they don’t match, then the token id is not valid. The payload contains personal data from the user, here is what is included in the payload:

{
  // These six fields are included in all Google ID Tokens.
  "iss": "https://accounts.google.com",
  "sub": "110169484474386276334", //Unique Google Account Id
  "azp": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
  "aud": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
  "iat": "1433978353",
  "exp": "1433981953",
  // These seven fields are only included when the user has granted the "profile" and
  // "email" OAuth scopes to the application.
  "email": "[email protected]",
  "email_verified": "true",
  "name": "Test User",
  "picture": "https://lh4.googleusercontent.com/-kYgzyAWpZzJ/ABCDEFGHI/AAAJKLMNOP/tIXL9Ir44LE/s99-c/photo.jpg",
  "given_name": "Test",
  "family_name": "User",
  "locale": "en"
}

Next, create an account or sign in the user if they already exist. The sub key in the payload is the Account Id and you can use to check if the user already exists. I suggest you generate your own User Id and do not rely with Google unique user id.

Implementing Login with Facebook with Angular and REST API

Today, I am going to show you how to create an Angular App with a REST API that uses Facebook Login to sign in/up users. For this …

Read More
Angular 5 – Handling Token Based Authentication

Token based authentication is popular for single page applications. A token is a security code issued by a server for authenticating and …

Read More
Search Engine Optimization with Angular

Today, I will show you how to optimize your Angular 5 and above for search engine and other crawlers. It is important to note that, pages …

Read More
Adaptive Layout Design - Angular Flex Layout

Introduction You probably have heard about Responsive Layout design but let me remind you anyway. Responsive layout is where components and …

Read More
Angular Material Icons Components with Angular 5

Icons are a necessity when building modern-day web apps and sometimes they can be frustrating. While icon sets like Font Awesome and …

Read More
Responsive Navbar with Angular Flex Layout

Today, we are going to create a responsive Navbar using Toolbar and Sidenav Components from Angular Material together with Angular Flex …

Read More

Comments