Home > Net >  Google Auth User Cryptic Properties
Google Auth User Cryptic Properties

Time:11-05

I'm using google auth on a web project and I'm trying to understand the property names. The screenshot shows the user object returned by google. I can access the id_token this way:

this.user.Zb.id_token

Why Zb? A year ago it was this:

this.user.wc.id_token

Notice it was wc back then and now my UI code breaks. What am I missing? Why are those property names used? How do I make it so I can access id_token regardless of its parent property name?

enter image description here

This is the UI code:

  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;
        });
    });
  }

CodePudding user response:

I don’t believe you’re using the SDK in its intended form; it’s not clear to me how you determined that this is the proper way to access the id_token value for the authenticated user as it’s not mentioned anywhere in the official docs.

signIn() returns an instance of GoogleUser, on which you can call getAuthResponse(). The returned gapi.auth2.AuthResponse object includes the 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)
      // …
  • Related