Google javascript client api : how to fetch profile name?

257 views Asked by At

I am trying to implement SignIn with Google with redirect approach. I am following this link My code looks like below

<script src="https://apis.google.com/js/platform.js?onload=startGoogleApp" async defer></script>
<script>

    var startGoogleApp = function () {
        gapi.load('auth2', function() {
            auth2 = gapi.auth2.init({
                client_id: '@googleClientId',
                ux_mode: 'redirect',
                redirect_uri: '@googleRedirectUri',
                fetch_basic_profile: true
            });

            auth2.signIn();
        });
    }
</script>

But issue is in Google's id_token is not having the name even though I have passed fetch_basic_profile: true I also tried with scope: 'profile'.

I want to fetch name along with email. don't know what am I doing wrong here. I want it in part of token as it is mentioned in documentation I am following. I don't want fetch name with additional api call. Is it possible? id_token looks like this

{
  "iss": "accounts.google.com",
  "azp": "*********",
  "aud": "***********",
  "sub": "*********",
  "hd": "***.com",
  "email": "*****@***.com",
  "email_verified": true,
  "iat": 1599717107,
  "exp": 1599720707,
  "jti": "*******"
}
1

There are 1 answers

0
Linda Lawton - DaImTo On

Googles Id token is not guaranteed to return all of the profile claims on ever response.

If you want the users profile information then you should go though the Google People API. people.get

 // Make sure the client is loaded and sign-in is complete before calling this method.
  function execute() {
    return gapi.client.people.people.get({
      "resourceName": "people/me",
      "requestMask.includeField": "addresses",
      "sources": [
        "READ_SOURCE_TYPE_PROFILE"
      ]
    })
        .then(function(response) {
                // Handle the results here (response.result has the parsed body).
                console.log("Response", response);
              },
              function(err) { console.error("Execute error", err); });
  }
  gapi.load("client:auth2", function() {
    gapi.auth2.init({client_id: "YOUR_CLIENT_ID"});
  });

Code ripped from the try me found on people.get