0

I've just installed the Google API 2.0, setup my application and I'm trying to authorize a user but I keep getting this error:

array(2) {
  ["error"]=>
  string(13) "invalid_grant"
  ["error_description"]=>
  string(20) "Malformed auth code."
}

for creating the authorization link I use the function $oGoogleClient->createAuthUrl(); within \Google_Client

it takes me to the authorization page and then returns to my authorization page with a code in the url like this:

http://example.com/authorize/?code=4/AABBv8nQ5N4mqrOTANDphl_L4ROPnzK6yckffDu-dnlIJGE9ZOcXo9eehUVbzbExbMuhCZQAb5zu9_BIS-VI4E4#

To handle this request I use the api funcion $oGoogleClient->fetchAccessTokenWithAuthCode($sCode); found in \Google_Client

At first I thought it was because of the # at the end of the code, because PHP only gets the code paramete until before that hashtag, so I hardcoded it to test, but the result is the same error message of Malformed Auth Code.

Any idea on how to solve this?

Update: I've moved the code to a different server, and it will authorize correctly the code and retrieve the Access Token. I guess it should be something within the server, but I can't figure out what!

Abraham Romero
  • 1,047
  • 11
  • 22

2 Answers2

1

I am using Node.js googleapis client library, Here is my case:

The authorization code in the url hash fragment is be encoded by encodeURIComponent api, so if you pass this code to request access token. It will throw an error:

{ "error": "invalid_grant", "error_description": "Malformed auth code." }

So I use decodeURIComponent to decode the authorization code.

decodeURIComponent('4%2F_QCXwy-PG5Ub_JTiL7ULaCVb6K-Jsv45c7TPqPsG2-sCPYMTseEtqHWcU_ynqWQJB3Vuw5Ad1etoWqNPBaGvGHY')

After decode, the authorization code is:

"4/_QCXwy-PG5Ub_JTiL7ULaCVb6K-Jsv45c7TPqPsG2-sCPYMTseEtqHWcU_ynqWQJB3Vuw5Ad1etoWqNPBaGvGHY"
Lin Du
  • 88,126
  • 95
  • 281
  • 483
0

Generally the URL is Encoded, So decode the URL and try again

Try URL Encode/Decode Tool click here

In python it can be done as below:

import requests
from urllib.parse import unquote
# Decode the url
query_str  = unquote(request.META.get('QUERY_STRING'))
 # Or just decode CODE
code = unquote(code)
data_dict = {
        "code": code, "redirect_uri":"", "grant_type": "authorization_code",
        "client_id": "","client_secret": ""
}
resp = requests.post('https://oauth2.googleapis.com/token', data_dict)
Amrit Prasad
  • 373
  • 6
  • 18