Tanuj Soni
Tanuj Soni

Reputation: 41

Google Oauth2 invalid_grant error while trying to refresh an access token

Scenario

I am trying to generate a Google OAuth2 access token with a supplied refresh token. The refresh token is obtain from the client side Javascript SDK, using the offline access method as mentioned in the following answer:
https://stackoverflow.com/a/49842793/16341841

The refresh token that's obtained is sent to the backend server, and the backend server tries to get a new access token using this refresh token whenever required. The API endpoint along with the request params being used for the same is:

curl --location --request POST 'https://oauth2.googleapis.com/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id=<my_client_id> \
--data-urlencode 'client_secret=<my_client_secret>' \
--data-urlencode 'refresh_token=<refresh_token_sent_by_frontend>' \
--data-urlencode 'grant_type=refresh_token'

Result (Error)

I receive the following error:

{
    "error": "invalid_grant",
    "error_description": "Bad Request"
}

What I have already tried

I have tried all applicable (literally all) solutions mentioned in the following link and internal links mentioned in the answers as well:
invalid_grant trying to get oAuth token from google

Notes

  1. The client id and client secret are the exact same on both frontend and backend.
  2. Whenever I generate a refresh token via Postman using OAuth2 APIs, I don't face any issues at all with token refresh using the same request as mentioned above. So I am assuming that I am doing the token refresh correctly on the backend.

What else could I be possibly missing? Would really appreciate some help here.

Upvotes: 4

Views: 1846

Answers (1)

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 117321

You are building the request wrong. Its a url string.

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

Understanding Google OAuth 2.0 with curl

Upvotes: 2

Related Questions