【问题标题】:Google Auth User Cryptic PropertiesGoogle Auth 用户加密属性
【发布时间】:2021-12-19 04:18:09
【问题描述】:

我在一个网络项目中使用 google auth,我正在尝试理解属性名称。截图显示了 google 返回的 user 对象。我可以通过这种方式访问​​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;
        });
    });
  }

【问题讨论】:

  • 我在 Google JavaScript SDK 文档的任何地方都找不到对这个属性的引用;您能否详细说明您在哪里了解到您应该以这种方式访问​​id_token
  • 如果我没记错的话,我只是记录了 google 的返回值,然后一直查看直到找到 id_token。它恰好在一个名为wc 的属性中,所以我只是在那里引用了它。它工作得很好,但现在,一年后,wc 属性是Zb

标签: javascript authentication google-oauth google-api-js-client


【解决方案1】:

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

signIn() 返回GoogleUser 的实例,您可以在其上调用getAuthResponse()。返回的gapi.auth2.AuthResponse object 包括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)
      // …

【讨论】:

  • 哦,哇,所以我不得不在返回的对象上调用一个方法来获得我需要的东西。让我试试……
  • 那行得通。谢谢!
猜你喜欢
  • 1970-01-01
  • 2020-01-09
  • 2012-11-18
  • 1970-01-01
  • 1970-01-01
  • 2017-08-22
  • 1970-01-01
  • 2015-01-14
  • 1970-01-01
相关资源
最近更新 更多