Angular javascript

[Angular]實作 Google 登入

周志衠 Jed Jhou 2020/11/16 16:01:24
2338

在專案中我們會遇到使用 google 或 fb 等等的社群登入需求,實作的部分一種是按照各家 api 文件自行串接,一種是在 npm 尋找對應的套件會相對容易,這裡使用 angularx-social-login 套件示範 google 登入。

 

申請 google 的 app client id

由此登入 Google API Console 並建立 client id。

步驟可參考以下截圖。



// google 的 client id 格式,依實際取得的 client id 為主
45047304xxxx-1m6hbqhps7f6siu79uqfdkgtcmuxxxxx.apps.googleusercontent.com

套件安裝

npm i angularx-social-login
 

匯入模組

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { GoogleLoginProvider, SocialAuthServiceConfig, SocialLoginModule } from 'angularx-social-login';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    SocialLoginModule
  ],
  providers: [
    {
      provide: 'SocialAuthServiceConfig',
      useValue: {
        autoLogin: true,
        providers: [
          {
            id: GoogleLoginProvider.PROVIDER_ID,
            provider: new GoogleLoginProvider(
              '45047304xxxx-1m6hbqhps7f6siu79uqfdkgtcmuxxxxx.apps.googleusercontent.com' // 於 google 申請的應用程式 client id
            )
          }
        ]
      } as SocialAuthServiceConfig
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

登入與登出

app.component.ts

import { Component, OnInit } from '@angular/core';
import { GoogleLoginProvider, SocialAuthService, SocialUser } from 'angularx-social-login';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  title = 'ngSocialloginDemo';

  user: SocialUser;
  loggedIn: boolean;

  constructor(private authService: SocialAuthService) { }

  ngOnInit(): void {
    this.authService.authState.subscribe((user) => {
      this.user = user;
    });
  }

  signInWithGoogle(): void {
    this.authService.signIn(GoogleLoginProvider.PROVIDER_ID);
  }

  signOut(): void {
    this.authService.signOut();
  }
}

資訊顯示

app.component.html

<div *ngIf="!user">
  <button (click)="signInWithGoogle()"><span>google</span></button>
</div>

<div *ngIf="user">
  <img *ngIf="user.photoUrl" src="{{ user.photoUrl }}">
  <div>
    <h4>{{ user.name }}</h4>
    <p>{{ user.email }}</p>
  </div>
  <button (click)="signOut()">Sign out</button>
</div>

到此已完成了在 Angular 中實作 google 登入過程,fb 登入也是一樣的方式,詳細可參考套件文件說明。

在登入後我們會取得基本的使用者資訊並開始操作相關 API 功能,按照 google 的建議流程,前端登入後應由後端在此檢查剛剛第一次取的的 token 是否為受信任的 client id 產生的,在這邊使用 web api 來示範如何驗證 google 的 token。

建立專案並安裝

於 VS 建立一個 .Net Framework Web API 專案後安裝以下 nuget 套件

Controller.cs

using Google.Apis.Auth;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Http;

namespace OAuthAPIDemo.Controllers
{
    public class SocialUser
    {
        public string Token { get; set; }
    }

    public class OAuthController : ApiController
    {
        [Route("api/OAuth")]
        [HttpPost]
        public async Task<IHttpActionResult> Post(SocialUser user)
        {
            var payload = await ValidateGoogleToken(user.Token);
            return Ok(payload);
        }


        private static async Task<GoogleJsonWebSignature.Payload> ValidateGoogleToken(string googleTokenId)
        {
            var settings = new GoogleJsonWebSignature.ValidationSettings
            {
                Audience = new List<string>() { "45047304xxxx-1m6hbqhps7f6siu79uqfdkgtcmuxxxxx.apps.googleusercontent.com" }
            };
            var payload = await GoogleJsonWebSignature.ValidateAsync(googleTokenId, settings);
            return payload;
        }
    }
}

在後端收到前端傳來的 idToken 後,再次和 google 驗證此 token 是否由同一個 client id 所產生,如果驗證成功,則會拿到完整的 palyload,可做後續處理,例如會員資料比對等流程。

周志衠 Jed Jhou