oauth-2.0google-oauthoauth2client

Unable to fetch access token and refresh token from google OAuth2.0 using the authorized code


I'm trying to get the access token and refresh token from google oauth2. Let me take you through one step at a time until I got the error. What I'm trying to do is straight out of documentation

  1. google console settings and credentials are well set. redirect uris from google cloud console

  2. Successfully received auth code using the following url that I pasted on my browser.

https://accounts.google.com/o/oauth2/v2/auth?scope=https://mail.google.com/&access_type=offline& include_granted_scopes=true&response_type=code&state=state_parameter_passthrough_value&redirect_uri=http://localhost&client_id=<client id>
code=4/0AcvDMrAjHZ9AeAhiQiE533rWoe6Hk4gmetvjfv-cY6nXMaaFB8BoVrxL-9-2ZLqjfMh50A
 

is the output that is got.

  1. trying to make a curl request using this auth code that I received from the previous step
curl --location 'https://oauth2.googleapis.com/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data 'code=4/0AcvDMrAjHZ9AeAhiQiE533rWoe6Hk4gmetvjfv-cY6nXMaaFB8BoVrxL-9-2ZLqjfMh50A&
client_id=<client id>&
client_secret=<client secret>&
redirect_uri=http://localhost&
grant_type=authorization_code'

Following is the output that I'm getting:

{
  "error": "unsupported_grant_type",
  "error_description": "Invalid grant_type: "
}

So, this is the error that i'm getting. I have rechecked my client id, secret, code, redirect_uri and everything looks correct. I'm not able to debug this issue. Could someone please help me resolve it?

My agenda is to access gmail apis. So, I have to do OAuth2.0 with google first. So, the steps are like, you need to get the auth code first using client Id. Then, upon getting that authcode, using that, need to make an another request to get the access token and refresh tokens to be able to use to further access gmail apis.

So, I'm keep getting this Invalid grant_type although I cross checked if I'm using the right scope, credentials, redirect URIs


Solution

  • Apparently there is some spacing issue with the request.

    I tried curl command again but with a little change. curl \ --request POST \ --data "code=<AuthCode>&client_id <ClientID>&client_secret=<ClientSecret>&redirect_uri=localhost&grant_type=authorization_code" \ oauth2.googleapis.com/token

    This worked for me