Many websites use Google SignIn as a way to login. Users can omit registration process and no longer need to remember an additional account. This article describes how to implement Google SignIn in Angular.
Table of Contents
Creating Google OAuth Credentials
First, we need to create an OAuth Credentials on the Google Console and obtain a ClientID. The following article explains the steps in detail.
The ClientID obtained in the article above is:
ClientID: 6nn16rjn23h8p11g8bkp2aogl4kqneuc.apps.googleusercontent.com
Setup GAPI
gapi is a library provided by Google to implement Google Sign In.
To use gapi, we must include platform.js in index.html because Google does not provide gapi that integrates Angular.
<head> <script src="https://apis.google.com/js/platform.js" async defer></script> </head>
However, fortunately there is a TypeScript declaration for gapi. At least we can use gapi with TypeScript.
% npm install --save-dev @types/gapi.auth2
Using GAPI
Add a service called LoginService, the code is as follows.
/// <reference types="gapi.auth2" /> import { Injectable, NgZone } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class LoginService { private auth: gapi.auth2.GoogleAuth; private user: gapi.auth2.GoogleUser; constructor(private zone: NgZone) { this.load() .then(() => this.init()) .then(auth => { this.auth = auth; }); } private load(): Promise<void> { return new Promise((resolve, reject) => { this.zone.run(() => { gapi.load('auth2', { callback: resolve, onerror: reject, }); }); }); } private init(): Promise<gapi.auth2.GoogleAuth> { return new Promise((resolve, reject) => { this.zone.run(() => { const auth = gapi.auth2.init({ client_id: '63245096424-6nn16rjn23h8p11g8bkp2aogl4kqneuc.apps.googleusercontent.com', scope: 'profile email', }); resolve(auth); }); }); } loginForUser(): Promise<gapi.auth2.GoogleUser> { return this.zone.run(() => { return this.auth.signIn() .then(user => { this.user = user; return user; }); }); } loginForCode(): Promise<{ code: string }> { return this.zone.run(() => { return this.auth.grantOfflineAccess() .then(response => { return response; }); }); } }
In the constructor, LoginService calls load() and init() to initialize gapi.auth2. After initialization, users click on a login button on screen, and you can call loginForUser() to login to Google. After success, it will return a GoogleUser, which contains basic profile and other user information.
You can also call loginForCode(), and it returns an Authorization Code. After that, you pass the Authorization Code to backend, and backend will authenticate the user with the Google OAuth Server. Finally, backend will obtain an ID Token. This is so-called Authorization Code Flow. For a detailed explanation of Authorization Code Flow and the logic of the backend part, you can refer to the following article.