Search code examples
curlgoogle-apigoogle-oauth

Invalid JSON payload received. Unexpected token.\nclient_id=xxxx\n^ error when use authCode to exchange access and refresh token


I'm used vue-google-oauth2 to get authCode from google, then I want to use it to exchange access and refresh token by below:

curl -d "client_id=0123456789012-xxxxxxxxxxx..apps.googleusercontent.com&\
  client_secret=MY_CLIENT_SECRET&\
  redirect_uri=postmessage&\
  grant_type=authorization_code&\
  code=MY_AUTH_CODE" -H "Content-Type: application/json" -H "Content-Type: application/x-www-form-urlencoded" --header 'Accept: application/json' https://accounts.google.com/o/oauth2/token

but I get an 400 error:

{
  "error": {
    "code": 400,
    "message": "Invalid JSON payload received. Unexpected token.\nclient_id=012345678\n^",
    "status": "INVALID_ARGUMENT"
  }
}

What I went wrong? Thanks for your support

To Reproduce

Replace client_id, client_secret, auth_code and run above Curl command

Expected behavior

Google OAuth response access token and refresh token


Solution

  • remove the returns you have \n in the string those /n's are confusing it.

    # Client id from Google Developer console
    # Client Secret from Google Developer console
    # Scope this is a space seprated list of the scopes of access you are requesting.
    
    # Authorization link.  Place this in a browser and copy the code that is returned after you accept the scopes.
    https://accounts.google.com/o/oauth2/auth?client_id=[Application Client Id]&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=[Scopes]&response_type=code
    
    # Exchange Authorization code for an access token and a refresh token.
    
    curl \
    --request POST \
    --data "code=[Authentcation code from authorization link]&client_id=[Application Client Id]&client_secret=[Application Client Secret]&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code" \
    https://accounts.google.com/o/oauth2/token
    
    # Exchange a refresh token for a new access token.
    curl \
    --request POST \
    --data 'client_id=[Application Client Id]&client_secret=[Application Client Secret]&refresh_token=[Refresh token granted by second step]&grant_type=refresh_token' \
    https://accounts.google.com/o/oauth2/token
    

    code from my curl example GoogleAuthenticationCurl.sh