Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Access Token from Refresh Token using cURL Google API

How to get a new Access Token from a Refresh Token using cURL?

In PHP, I would do something like this:

$client = new Google_Client();
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$client->refreshToken($refresh_token);
$access_token = $client->getAccessToken();

How to accomplish the same thing using cURL?

I was unable to find it from their documentation.

like image 878
Silver Ringvee Avatar asked Oct 08 '19 11:10

Silver Ringvee


People also ask

Can refresh token be used as access token?

Refresh tokens are the credentials that can be used to acquire new access tokens. The lifetime of a refresh token is much longer compared to the lifetime of an access token.

How do I get access token and refresh token OAuth2?

Step 1 − First, the client authenticates with the authorization server by giving the authorization grant. Step 2 − Next, the authorization server authenticates the client, validates the authorization grant and issues the access token and refresh token to the client, if valid.


1 Answers

This is the code I use:

# 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

Link to gist


The full flow with cURL

# 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
like image 120
DaImTo Avatar answered Sep 30 '22 07:09

DaImTo