Search code examples
javascriptjquery-mobilegoogle-books

Google access_token is undefined


I am developing a mobile web application which will access the Google Books API and allow the user to add books to their "favorites" book shelf. Its my first time using an API that requires the Google authorization.

I need to send an authorized request to modify private user data. I (think) I have have the proper access_token but I can't figure out how to get to it.

I am using the Google sign in button like so:

` <div class="g-signin2" data-onsuccess="onSignIn"></div> `

I also have this to identify my application to Google:

`<meta name="google-signin-client_id" content="12345.apps.googleusercontent.com"> `

I sign in with my own Google account and the Google button changes over to "Signed In." I am simply trying to log the access token from there:

` function onSignIn(googleUser) {
  googly = gapi.auth2.getAuthInstance();
  var id_token = googly.currentUser.get().getAuthResponse().access_token; 
  console.log(id_token); 
} `

I've tried everything I can find in the documentation but no matter what I do, I get back that access_token is undefined.

My suspicion is that I don't actually have an access token, but I don't know how to test that.

What is the correct way to find the access_token? Once I have it, how do I send it to the API?


Solution

  • Try using gapi.auth in the API Client Library instead of gapi.auth2 in the Identify Platform. You should find gapi.auth.getToken().access_token contains the access token you need.


    That said, I believe this is a bug. If you alert(JSON.stringify(googleUser)) I suspect you'll find there is an access_token field buried in there, but getAuthResponse() doesn't contain it, even though the docs suggest there should be one.

    If anyone can confirm I'm understanding this correctly and report it, that would be great.


    If you include the response_type in the request header as 'token' it will return the access_token with the currentUser