网站搜索

TypeScript - 如何在 Angular 2+ 中使用最新的 Google 身份服务实现 Google 登录


谷歌已弃用旧的 Google Sign JavaScript 实现。我们应该开始使用新的身份服务。在 Angular 中如何实现这个?

答案#1

我们假设您已经拥有此类服务的 Google 密钥(Google 客户端 ID),因此我们将继续在 Angular 应用中集成新的 Google 登录身份服务。

  1. 作为一种良好的做法,我们在环境文件中添加变量 googleClientId,并使用上面提到的我们的 Google 密钥。

export const environment = {
  ...
  googleClientId: 'YOUR_GOOGLE_CLIENT_ID',
};
  1. 在 index.html 文件中,我们添加 Google 脚本,这将允许我们使用此功能。

<!doctype html>
<html lang="en">
<head>
  ...
</head>
<body>
  <app-root></app-root>
  <script src="https://accounts.google.com/gsi/client" async defer></script>
</body>
</html>
  1. 我们安装 Google One Tap 类型包(@types/google-one-tap)来帮助我们进行集成(可选)。

  2. 在我们将要使用此功能的组件中,在 .ts 文件中我们声明了 google 全局变量。在 ngAfterViewInit 钩子中,我们通过引用分配给 HTML 元素的 id 来初始化按钮并渲染它,该 HTML 元素是 iframe 将要被注入的地方。在初始化方法中,callback 是我们收集 Google 登录时返回的令牌的地方,我们使用 ngZone 是因为导航将在 Angular 区域之外触发。

declare var google: any;

import { AfterViewInit, Component, ElementRef, NgZone } from '@angular/core';
import { accounts } from 'google-one-tap';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'app-login-page',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
})
export class LoginPageComponent implements AfterViewInit {
  constructor(private ngZone: NgZone) {}

  ngAfterViewInit() {
    const gAccounts: accounts = google.accounts;

    gAccounts.id.initialize({
      client_id: environment.googleClientId,
      ux_mode: 'popup',
      cancel_on_tap_outside: true,
      callback: ({ credential }) => {
        this.ngZone.run(() => {
          this._loginWithGoogle(credential);
        });
      },
    });

    gAccounts.id.renderButton(document.getElementById('gbtn') as HTMLElement, {
      size: 'large',
      width: 320,
    });
  }

  private _loginWithGoogle(token: string) {
    ...
  }
}

答案#2

在2022年7月29日之前创建的新客户端ID可以使用较旧的Google平台库。默认情况下,新创建的客户端ID现在被阻止使用该平台库,而必须使用较新的Google身份服务库。您可以选择任何值,建议使用描述性名称,例如产品或插件名称,以便于识别。

示例:plugin_name: 'login'。

请阅读我的文章《使用 OAuth 2.0 的 Angular 14 Google 登录》,我在文章中逐步解释了所有内容。

googleAuthSDK() {

    (<any>window)['googleSDKLoaded'] = () => {
      (<any>window)['gapi'].load('auth2', () => {
        this.auth2 = (<any>window)['gapi'].auth2.init({
          client_id: 'YOUR CLIENT ID',
          plugin_name:'login',
          cookiepolicy: 'single_host_origin',
          scope: 'profile email'
        });
        this.callLogin();
      });
    }