首页 > 解决方案 > Google Auth 用户加密属性

问题描述

我在一个网络项目上使用谷歌身份验证,我试图理解属性名称。屏幕截图显示了usergoogle 返回的对象。我可以通过id_token这种方式访问​​:

this.user.Zb.id_token

为什么Zb?一年前是这样的:

this.user.wc.id_token

请注意,那是wc当时,现在我的 UI 代码中断了。我错过了什么?为什么使用这些属性名称?如何制作它以便id_token无论其父属性名称如何我都可以访问?

在此处输入图像描述

这是用户界面代码:

  async authenticate(): Promise<gapi.auth2.GoogleUser> {
    // Initialize gapi if not done yet
    if (!this.gapiSetup) {
      await this.initGoogleAuth();
    }

    // Resolve or reject signin Promise
    return new Promise(async () => {
      await this.authInstance.signIn().then(
        user => {
          this.user = user;
          console.log('this.user: ', this.user);
          
          this.cookieService.set('jwt', this.user.Zb.id_token, 365); // expires in one year (365 days)
          // this.cookieService.set('jwt', this.user.wc.id_token, 365); // expires in one year (365 days)

          this.owlerApiService.getHooterUsingIdTokenFromProvider()
            .subscribe((data: any) => {
              this.userDto = data;            
            },
            error => {
              console.log('error: ', error);
            });
        },
        error => this.error = error);
    });
  }

  async initGoogleAuth(): Promise<void> {
    // Create a new Promise where the resolve function is the callback passed to gapi.load
    const pload = new Promise((resolve) => {
      gapi.load('auth2', resolve);
    });

    // When the first promise resolves, it means we have gapi loaded and that we can call gapi.init
    return pload.then(async () => {
      // ClientId safe to put here? Looks like it:
      // https://stackoverflow.com/a/62123945/279516
      await gapi.auth2
        .init({ client_id: 'xxx.apps.googleusercontent.com' })
        .then(auth => {
          this.gapiSetup = true;
          this.authInstance = auth;
        });
    });
  }

标签: javascriptauthenticationgoogle-oauthgoogle-api-js-client

解决方案


我不相信您正在以预期的形式使用 SDK;我不清楚您如何确定这是访问经过id_token身份验证的用户的值的正确方法,因为官方文档中的任何地方都没有提到它。

signIn()返回 的实例GoogleUser,您可以在其上调用getAuthResponse()。返回的gapi.auth2.AuthResponse对象包括id_token

await this.authInstance.signIn().then(
    user => {
      this.user = user;
      console.log('this.user: ', this.user);
      
      this.cookieService.set('jwt', this.user.getAuthResponse().id_token, 365); // expires in one year (365 days)
      // …

推荐阅读