Help: Uncaught exception 'apiAuthException' with message 'Could not json decode the access token'

7,024 views
Skip to first unread message

cameron.g.brown

unread,
Jun 30, 2011, 9:09:11 PM6/30/11
to google-api-php-client
Any help appreciated... I'm trying to use oAuth2 to access Google
Docs, but I'm having trouble.

I'm getting this output:

--start paste--

PHP Fatal error: Uncaught exception 'apiAuthException' with message
'Could not json decode the access token' in /usr/lib/PHP/google-api-
php-client/src/auth/apiOAuth2.php:91
Stack trace:
#0 /usr/lib/PHP/google-api-php-client/src/apiClient.php(159):
apiOAuth2->setAccessToken(NULL)
#1 /Users/Cam/Apps/Serinette/Workshop/EngineRoom_OFFLINE/
GoogleDoc2Roll/GoogleDoc2Roll.php(40): apiClient->setAccessToken(NULL)
#2 {main}
thrown in /usr/lib/PHP/google-api-php-client/src/auth/apiOAuth2.php
on line 91

--end paste--

Looks like the problem is setAccessToken(NULL), but I don't know how
to make it not be NULL! Here is my code:

--start paste--

session_start();
require_once 'src/apiClient.php';

global $apiConfig;
$apiConfig['oauth2_client_id'] = 'redacted'; //I have registered and
received a client_id
$apiConfig['oauth2_client_secret'] = 'redacted'; //I have a client
secret

$apiConfig['oauth2_redirect_uri'] = 'http://localhost'; //this is a
desktop app. I've also tried the 'urn:ietf:wg:oauth:2.0:oob' version
and get the same error
$apiConfig['authClass'] = 'apiOAuth2';

$client = new apiClient();

if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
} else {
$client->setAccessToken($client->authenticate());
}

--end paste--

I guess $client->authenticate is failing... and when I look in
apiOAuth2.php it looks like authenticate() wants params... but none of
the sample code I can find passes any params in. I'm kind of a PHP
n00b so I'm not sure what's going on here.

Can anyone help?

Chirag Shah

unread,
Jun 30, 2011, 9:20:08 PM6/30/11
to google-api...@googlegroups.com
Hey Cameron,

The value for oauth2_redirect_uri should be:
urn:ietf:wg:oauth:2.0
Also the method $client->authenticate() is a bit overloaded, and sets the Location header when the user needs to grant Authorization to the app, but doesn't surface it.

I recently added the method to surface the authorization url since it's required when authorization is out-of-band.

Here's an example of how it is used:
<?php
require_once '../../src/apiClient.php';
require_once '../../src/contrib/apiBuzzService.php';

defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));

global $apiConfig;

// generate your oauth2_client_id, oauth2_client_secret, and to
// register your oauth2_redirect_uri.
//$apiConfig['oauth2_client_id'] = 'INSERT_CLIENT_ID';
//$apiConfig['oauth2_client_secret'] = 'INSERT_CLIENT_SECRET';
$apiConfig['oauth2_redirect_uri'] ='urn:ietf:wg:oauth:2.0:oob';
$apiConfig['authClass'] ='apiOAuth2';

$client = new apiClient();
$buzz = new apiBuzzService($client);

$authUrl = $client->createAuthUrl();

print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));

$_GET['code'] = $authCode;
$accessToken = $client->authenticate();

var_dump($accessToken);

Thank you,
Chirag Shah

Florian Schödel

unread,
Oct 25, 2011, 2:22:50 AM10/25/11
to google-api...@googlegroups.com
I have the same problem as mentioned above; "... could not json decode the access token...". I have traced this issue and realized, that 'getResponseBody()' of 'apiCurlIO' also delivers the http response header instead of only the body. 

this seems to be the reason why it fails. In my environment I had to add proxy settings within apiCurlIO. I try to investigate if my http proxy is modifying the result, 'makeRequest()' looks very error-prone.... :( 

"...
 list($rawResponseHeaders, $responseBody) = explode("\r\n\r\n", $data, 2);
        $responseHeaderLines = explode("\r\n", $rawResponseHeaders);
        array_shift($responseHeaderLines);
        $responseHeaders = array();
       
..."

something went wrong within this lines, if you use a squid :(



Florian Schödel

unread,
Oct 25, 2011, 2:30:12 AM10/25/11
to google-api...@googlegroups.com
ok, I've got it: 

my proxy add's    "HTTP/1.0 200 Connection established" at the beginning of the response; google's client api interprets this as the "header" and the real header as "body". and the "real body" is ignored :(


Chirag Shah

unread,
Oct 27, 2011, 2:12:22 PM10/27/11
to google-api...@googlegroups.com
Hi Florian,
Thank you for reporting this issue! This should now be fixed in trunk.
Can you check out the latest version of the client library, and give it a spin?

Thank you!
Chirag Shah

Hugo Leon

unread,
Nov 7, 2011, 2:26:26 AM11/7/11
to google-api...@googlegroups.com
I have the same problem, so checked out the latest version (255) but unfortunately doesn't work yet...
Running a test into localhost worked succesfully.

What else could it be?

Thanks!

Chirag Shah

unread,
Nov 7, 2011, 11:46:12 AM11/7/11
to google-api...@googlegroups.com
Hey Hugo,

What does the response look like? Does your proxy add "HTTP/1.0 200 Connection established" in the response?

Øyvind Repvik

unread,
Dec 7, 2011, 4:27:42 AM12/7/11
to google-api...@googlegroups.com
I'm getting this:

Fatal error: Uncaught exception 'apiAuthException' with message 'Could not json decode the access token' in /path/includes/gapi/auth/apiOAuth2.php:136 Stack trace: #0 /path/includes/gapi/auth/apiOAuth2.php(99): apiOAuth2->setAccessToken('er: GSE??Transf...') #1 /path/includes/gapi/apiClient.php(132): apiOAuth2->authenticate(Array) #2 /path/gcal.php(17): apiClient->authenticate() #3 {main} thrown in /path/includes/gapi/auth/apiOAuth2.php on line 136 

The string in setAccessToken looks a lot like headers; 
X-XSS-Protection: 1; mode=block 
Server: GSE
Transfer-Encoding: chunked

Øyvind Repvik

unread,
Dec 7, 2011, 6:21:05 AM12/7/11
to google-api...@googlegroups.com
Ugly hack: in apiCurlIO.php round line 118, I added $respData=substr($respData,38);
That removes the HTTP/1.1 200 Connection established header.

Chirag Shah

unread,
Dec 7, 2011, 12:28:24 PM12/7/11
to google-api...@googlegroups.com
Hey Øyvind,

From looking at the line numbers in the stack trace, It looks like you're using an older version of the client library.

Can you try upgraded to the latest version of the client library? This issue should be fixed in the latest version.

Thank you,
Chirag

Øyvind Repvik

unread,
Dec 7, 2011, 12:37:15 PM12/7/11
to google-api...@googlegroups.com
I was using the last tarball (downloaded two days ago), but I had to
add a couple of lines to tell curl how to access the proxy I'm behind,
which offset the line numbers a bit. I got the same result from todays
trunk.

--
Øyvind Repvik
rep...@gmail.com
+47 90 80 40 02

pas

unread,
Oct 22, 2012, 5:48:01 AM10/22/12
to google-api...@googlegroups.com, rep...@gmail.com
Hi all, I would have a similar problem and it is the first time I use the google api and I do not know how to solve the following problem:

Fatal error: Uncaught exception 'Google_AuthException' with message 'Could not json decode the token' in /membri/hitechsideforum/google-api-php-client/src/auth/Google_OAuth2.php:156 Stack trace: #0 /membri/hitechsideforum/google-api-php-client/src/auth/Google_OAuth2.php(105): Google_OAuth2->setAccessToken('me-Options: SAM...') #1 /membri/hitechsideforum/google-api-php-client/src/Google_Client.php(131): Google_OAuth2->authenticate(Array, '4/5yvb3LvwIwGsA...') #2 /membri/hitechsideforum/google_examples/userinfo.php(20): Google_Client->authenticate('4/5yvb3LvwIwGsA...') #3 {main} thrown in /membri/hitechsideforum/google-api-php-client/src/auth/Google_OAuth2.php on line 156

 if ($request->getResponseHttpCode() == 200) {
        echo "BODY: \n".$request->getResponseBody();
        $this->setAccessToken($request->getResponseBody());
        $this->token['created'] = time();
        return $this->getAccessToken();
      }

By debugging mold the content of the response in JSON, the answer seems to be correct, but at this point I do not know what to do, someone could tell me how to solve this error?
Thanks to all

pas

Aza Steel

unread,
Nov 4, 2013, 3:46:38 PM11/4/13
to google-api...@googlegroups.com, rep...@gmail.com
So I solved my issue by grabbing the access_token from the Session variable, and re-encoding a JSON object.  It expects it to be encoded as JSON, it does not want it to be objectified (lol) already.  This is the code in the setAccessToken that throws the error:

    $token = json_decode($token, true);
    if ($token == null) {
      throw new Google_AuthException('Could not json decode the token');
    }
    if (! isset($token['access_token'])) {
      throw new Google_AuthException("Invalid token format");
    }


This code solved it for me: 

        $token = $_SESSION['access_token'];
$tokenObj = array('access_token' => $token);
$tokenObj = json_encode($tokenObj);
$client->setAccessToken($tokenObj);

Hope that helps someone!

jyoti prakash sahoo

unread,
Nov 8, 2013, 1:51:34 AM11/8/13
to google-api...@googlegroups.com
Hi All,
need a urgent help.I am also using a proxy connection and getting a authentication error.

Uncaught exception 'Google_IOException' with message 'HTTP Error: (0) Received HTTP code 400 from proxy after CONNECT' in /var/www/html/google-api-php-client/src/io/Google_CurlIO.php:136 Stack trace: #0 /var/www/html/google-api-php-client/src/auth/Google_OAuth2.php(104): Google_CurlIO->makeRequest(Object(Google_HttpRequest)) #1 /var/www/html/google-api-php-client/src/Google_Client.php(127): Google_OAuth2->authenticate(Array, '4/qglpxAMtqV8IP...') #2 /var/www/html/google-api-php-client/examples/calendar/simple.php(28): Google_Client->authenticate('4/qglpxAMtqV8IP...') #3 {main} thrown in /var/www/html/google-api-php-client/src/io/Google_CurlIO.php on line 136

Any possible reason,Pls help.

Pasquale 86

unread,
Nov 8, 2013, 10:29:48 AM11/8/13
to google-api...@googlegroups.com
Hi, I solved by applying a slight modification to the class Google_REST.php , it would be better not to fix it , but I have not found other solutions, however, it may be helpful , in my case the token encoded in JSON format was transmitted according to this here : Protection : 1; mode = block Server : GSE Alternate- Protocol: 443: quic Transfer-Encoding: chunked and after {key : value , key: value , etc. } .

For some reason unknown to me , were added in most of the information that was not necessary that , at the time of decoding the JSON format , obviously returned NULL , probably due to an error in JSON format.

I simply used a regex to remove the part before the "{" , namely:

The method decodeHttpResponse I changed to this:

  /**
   * Decode an HTTP Response.
   * @static
   * @throws Google_ServiceException
   * @param Google_HttpRequest $response The http response to be decoded.
   * @return mixed|null
   */
  public static function decodeHttpResponse($response) {
    $code = $response->getResponseHttpCode();
    $body = $response->getResponseBody();
    $decoded = null;
    if ((intVal($code)) >= 300) {
      //*********************BUG RISOLTO********************
      echo "<br>TOKEN PRIMA: ".$body."<br>";
      $pattern = '/{.*}/';
      preg_match($pattern, $body, $body);
      echo "<br>TOKEN DOPO: ";
      print_r($body[0]);
      //****************************************************
      $decoded = json_decode($body[0], true);
      //$decoded = json_decode($body, true);
      $err = 'Error calling ' . $response->getRequestMethod() . ' ' . $response->getUrl();
      if ($decoded != null && isset($decoded['error']['message'])  && isset($decoded['error']['code'])) {
        // if we're getting a json encoded error definition, use that instead of the raw response
        // body for improved readability
        $err .= ": ({$decoded['error']['code']}) {$decoded['error']['message']}";
      } else {
        $err .= ": ($code) $body";
      }

      throw new Google_ServiceException($err, $code, null, $decoded['error']['errors']);
    }
    
    // Only attempt to decode the response, if the response code wasn't (204) 'no content'
    if ($code != '204') {
      //*********************BUG RISOLTO********************
      echo "<br>TOKEN PRIMA: ".$body."<br>";
      $pattern = '/{.*}/';
      preg_match($pattern, $body, $body);
      echo "<br>TOKEN DOPO: ";
      print_r($body[0]);
      //****************************************************
      $decoded = json_decode($body[0], true);
      //$decoded = json_decode($body, true);
      if ($decoded === null || $decoded === "") {
        throw new Google_ServiceException("Invalid json in service response: $body");
      }
    }
    return $decoded;
  }

I hope to be helpful in some way. Let me know if you have solved another way.

Bye.

PS : Another tip is to try to download the latest version of the Google API , maybe the problem resolves itself .


2013/11/8 jyoti prakash sahoo <jyotiaeng...@gmail.com>

--
You received this message because you are subscribed to a topic in the Google Groups "google-api-php-client" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/google-api-php-client/MewNyTT92vU/unsubscribe.
To unsubscribe from this group and all its topics, send an email to google-api-php-c...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Reply all
Reply to author
Forward
0 new messages