Search code examples
google-apigoogle-oauthgoogle-fit-api

Google Rest Apis and google sign in


I've successfully used the google sign in library to create a google sign-in button, request additional scopes however I'm having trouble figuring out how to translate this into a API request. I'm using googleUser.getAuthResponse().id_token and getting a token but I'm not sure how to translate this into an access token to send along with my API requests?

I'm using pretty much just what the documentation has:

    function onSignIn(googleUser) {
    var profile = googleUser.getBasicProfile();

    document.getElementById("acc").src = profile.getImageUrl();
    console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
    console.log('Name: ' + profile.getName());
    console.log('Image URL: ' + profile.getImageUrl());
    console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
    
    var oAuthToken = googleUser.getAuthResponse().id_token
    }

Solution

  • The ID Token returned by Google Sign-In is not accepted as a credential for any Google APIs. It is intended only for passing to your backend so you can securely identify the user there.

    You need an Access Token to call Google APIs. The token can be retrieved in your onSignIn method with googleUser.getAuthResponse(true).access_token. This will only be present if you've requested scopes other than basic profile scopes, which you'd need for API access anyway.

    Google Sign-In is built on top of GAPI. Once the user is signed-in, you can check gapi.auth2.getAuthInstance().isSignedIn.get() to verify the user is signed in, as far as GAPI is concerned. At this point, using GAPI to call Google APIs will attach credentials to the request to Google's servers.