很多網站利用 Google SignIn 作為登入的途徑。用戶可以省略註冊的流程,也不需要再額外記住一組帳號。本文章介紹如何在 Angular 中實作 Google SignIn。
Table of Contents
建立 Google OAuth Credentials
首先,我們先在 Google Console 上建立 OAuth Credentials,並取得 ClientID。下面的文章有詳細解釋步驟。
文章中取得的 ClientID 為:
ClientID: 6nn16rjn23h8p11g8bkp2aogl4kqneuc.apps.googleusercontent.com
設定 GAPI
gapi 是 Google 提供用來實作 Google Sign In 的函式庫。
要使用 gapi,我們必須要在 index.html 中引入 platform.js。因為 Google 並沒有提供整合 Angular 的 gapi。
<head> <script src="https://apis.google.com/js/platform.js" async defer></script> </head>
不過,所幸有 gapi 的 TypeScript 宣告檔。至少我們可以用 TypeScript 來使用 gapi。
% npm install --save-dev @types/gapi.auth2
使用 GAPI
新增一個 service 叫 LoginService,程式碼如下。
/// <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;
});
});
}
}在建構子中,LoginService 呼叫 load() 和 init() 來初始化 gapi.auth2。初始化之後,用戶在畫面上點擊登入按鈕,你可以呼叫 loginForUser() 來登入到 Google。登入成功後,它會回傳 GoogleUser,而裡面包含了基本的 Profile 等用戶資訊。
你也可以呼叫 loginForCode(),而它會回傳 Authorization Code。之後,你可以將 Authorization Code 傳給後端,後端再去跟 Google OAuth Server 驗證用戶。最後,後端會取得 ID Token。這也就所謂的 Authorization Code Flow。關於 Authorization Code Flow 的詳細解說,以及後端部分的邏輯,可以參考下面的文章。




