介紹
最近,越來越多的網站使用 Google 登入來替代原有的登錄方式,對用戶來說可以節省大量的時間和精力,不需要再去記憶一組新密碼,而更加輕鬆地進行登錄。對網站本身的優點是不需要儲存使用者的密碼等等。
而 Angular 是一種用來開發響應式 Web 應用的框架,它可以幫助我們快速構建出美觀又高效的網站。在本文中,我們將探究如何使用 Angular 做 Google 登入。
設定 Google 登入
接下來,我們需要設置 Google 登入,我們需要新建一個 Google API 密鑰,然後複製到 Angular 應用中。可以在 Google API 控制台中找到 API 密鑰,然後將其複製到 Angular 應用中,以便讓 Angular 能夠連接 Google 的身份驗證系統。
1. 登入 Google Cloud Console
2. 選擇憑證 -> 建立憑證 -> OAuth 用戶端 ID
3. 已授權的 Javascript 來源加上 http://localhost 和 http://localhost:<port_number>
4. 建立完成後,Google 就會提供用戶端 ID 和用戶端密碼。
實做 Google 登入
最後,我們需要實做 Google 登入的功能。
1. 輸入指令:npm i @abacritt/angularx-social-login
2. 匯入模組: app.module.ts
◾️ 匯入 SocialAuthServiceConfig, SocialLoginModule, GoogleLoginProvider
◾️ clientId 要替換成剛才生成的 clientId
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {
SocialAuthServiceConfig,
SocialLoginModule,
GoogleLoginProvider,
} from '@abacritt/angularx-social-login';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, AppRoutingModule, SocialLoginModule],
providers: [
{
provide: 'SocialAuthServiceConfig',
useFactory: () => {
const clientId =
'917270506123-vgm34qorth027m8uuk4sohso57a0u4b4.apps.googleusercontent.com';
const socialAuthServiceConfig: SocialAuthServiceConfig = {
autoLogin: false,
providers: [
{
id: GoogleLoginProvider.PROVIDER_ID,
provider: new GoogleLoginProvider(clientId),
},
],
onError: (err) => {
console.error(err);
},
};
return socialAuthServiceConfig;
},
},
],
bootstrap: [AppComponent],
})
export class AppModule {}
3. app.component.html
◾️ 當 user 不是空的,代表 user 已經 logged in
◾️ SocialUser object 包含一些 user 的基本資料,如 photoUrl, name, email
<asl-google-signin-button type='icon' size='medium'></asl-google-signin-button>
<div *ngIf="user">
<img src="{{ user.photoUrl }}" referrerpolicy="no-referrer">
<div>
<h4>{{ user.name }}</h4>
<p>{{ user.email }}</p>
</div>
</div>
4. app.component.ts
◾️ getAccessToken: 取得用戶當前的 AccessToken
◾️ refreshAuthToken: 當 user 登入時,refreshAuthToken method 會被觸發
◾️ refreshAccessToken: 當 user 登入時,拿到的 access token 可以被 refresh
◾️ signOut: 登出
import { Component, OnInit } from '@angular/core';
import {
SocialAuthService,
SocialUser,
GoogleLoginProvider,
} from '@abacritt/angularx-social-login';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
title = 'moneyTracker';
user: SocialUser | undefined;
private accessToken: string | undefined;
get loggedIn() {
return this.user != null;
}
constructor(private authService: SocialAuthService) {}
ngOnInit() {
this.authService.authState.subscribe((user) => {
this.user = user;
});
}
async getAccessToken() {
this.accessToken = await this.authService.getAccessToken(
GoogleLoginProvider.PROVIDER_ID
);
return this.accessToken;
}
async refreshAuthToken() {
await this.authService.refreshAuthToken(GoogleLoginProvider.PROVIDER_ID);
}
async refreshAccessToken() {
await this.authService.refreshAccessToken(GoogleLoginProvider.PROVIDER_ID);
}
async signOut() {
await this.authService.signOut();
}
}
結論
通過以上的步驟,我們可以使用 Angular 做 Google 登入,節省大量的時間和精力,讓用戶可以更加輕鬆地進行登錄。
參考資料
- https://github.com/abacritt/angularx-social-login
- The given origin is not allowed for the given client ID (GSI)
- TypeScript Getters and Setters