87

I have completed steps of authorization and obtained access token and refresh token.

What should I do next to generate access token using refresh token that I have stored through google drive API?

I won't be able to use any sdk since I am working on Force.com so please suggest the way to implement it directly through the API.

Mohammed H
  • 6,880
  • 16
  • 81
  • 127
Niranja
  • 1,451
  • 2
  • 18
  • 19

10 Answers10

62

If you are using web api then you should make a http POST call to URL : https://www.googleapis.com/oauth2/v4/token with following request body

client_id: <YOUR_CLIENT_ID>
client_secret: <YOUR_CLIENT_SECRET>
refresh_token: <REFRESH_TOKEN_FOR_THE_USER>
grant_type: refresh_token

refresh token never expires so you can use it any number of times. The response will be a JSON like this:

{
  "access_token": "your refreshed access token",
  "expires_in": 3599,
  "scope": "Set of scope which you have given",
  "token_type": "Bearer"
}
Prajna
  • 578
  • 4
  • 8
  • 23
Ashutosh Singh
  • 721
  • 5
  • 9
  • 2
    working pragmatically with httpclient, not working from postman in may case as well. –  May 27 '17 at 23:25
  • 1
    This seems to be the right direction, but it's not working for me either. I've asked a question with details here if someone can help : https://stackoverflow.com/questions/48775759/google-oauth-403-when-refreshing-access-token – Jérôme S. Feb 14 '18 at 09:39
  • 2
    where do you get the client_secret from and the refresh token? – Jono Jul 15 '19 at 15:41
  • 1
    this is not working for me. it says unauthorized and invalid client – user0918232 Jun 26 '20 at 09:48
  • the client_secrets and client_id can be obtained from the Google Developers console, in the credentials tab of your project. Open https://console.developers.google.com/apis/dashboard – Masroor Oct 09 '20 at 11:12
  • I found this the best answer, just want to add an object format for php `$client->setAccessToken( [ "access_token" => $access_token, "token_type" => $token_type, "expires_in" => $expires_in, "refresh_token" => $refresh_token, "created" => $user->created, "scope" => "https://www.googleapis.com/auth/calendar" ] );` – Zia Dec 13 '21 at 12:46
  • If refresh token never expires, why is there a "expires_id" field? P.s my refresh token is expiring after every hour. – Abdul Haq Mar 26 '22 at 17:10
35

If you want to implement that yourself, the OAuth 2.0 flow for Web Server Applications is documented at https://developers.google.com/accounts/docs/OAuth2WebServer, in particular you should check the section about using a refresh token:

https://developers.google.com/accounts/docs/OAuth2WebServer#refresh

Claudio Cherubino
  • 14,896
  • 1
  • 35
  • 42
  • The documents you mentioned are dealing with only Raw-HTTP communication. Is there any method in PHP-API for refreshing tokens? – Mohammed H Dec 07 '12 at 13:08
  • @ClaudioCherubino ..i m sorry to interrupt u..but could u plz tell me . is it possible to get authorized url of google drive, which can be used publicly like playing audio and video with browser pr player..in iOS – NextStep Sep 23 '13 at 07:28
  • 1
    I dont wanted to imlement it myself. can somebody provide a sample code using google apis? – Vishnudev K Oct 15 '13 at 19:59
33

It's an old question but seems to me it wasn't completely answered, and I needed this information too so I'll post my answer.

If you want to use the Google Api Client Library, then you just need to have an access token that includes the refresh token in it, and then - even though the access token will expire after an hour - the library will refresh the token for you automatically.

In order to get an access token with a refresh token, you just need to ask for the offline access type (for example in PHP: $client->setAccessType("offline");) and you will get it. Just keep in mind you will get the access token with the refresh token only in the first authorization, so make sure to save that access token in the first time, and you will be able to use it anytime.

Hope that helps anyone :-)

amosmos
  • 1,039
  • 10
  • 20
14

All you need to do is a post request like below :-

POST https://www.googleapis.com/oauth2/v4/token
Content-Type: application/json

{
  "client_id": <client_id>,
  "client_secret": <client_secret>,
  "refresh_token": <refresh_token>,
  "grant_type": "refresh_token"
}
Raad Altaie
  • 1,025
  • 1
  • 15
  • 28
6

Just posting my answer in case it helps anyone as I spent an hour to figure it out :)

First of all two very helpful link related to google api and fetching data from any of google services:

https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/web-php

https://developers.google.com/identity/protocols/OAuth2WebServer

Furthermore, when using the following method:

$client->setAccessToken($token)

The $token needs to be the full object returned by the google when making authorization request, not the only access_token which you get inside the object so if you get the object lets say:

{"access_token":"xyz","token_type":"Bearer","expires_in":3600,"refresh_token":"mno","created":1532363626}

then you need to give:

$client->setAccessToken('{"access_token":"xyz","token_type":"Bearer","expires_in":3600,"refresh_token":"mno","created":1532363626}')

Not

$client->setAccessToken('xyz')

And then even if your access_token is expired, google will refresh it itself by using the refresh_token in the access_token object.

Abhay Maurya
  • 11,819
  • 8
  • 46
  • 64
6

If you using Java then follow below code snippet :

GoogleCredential refreshTokenCredential = new GoogleCredential.Builder()
    .setJsonFactory(JSON_FACTORY)
    .setTransport(HTTP_TRANSPORT)
    .setClientSecrets(CLIENT_ID, CLIENT_SECRET)
    .build()
    .setRefreshToken(yourOldToken);
refreshTokenCredential.refreshToken(); //do not forget to call this
String newAccessToken = refreshTokenCredential.getAccessToken();
Westy92
  • 19,087
  • 4
  • 72
  • 54
Divyesh Kanzariya
  • 3,629
  • 3
  • 43
  • 44
6

Using Post call, worked for me.

RestClient restClient = new RestClient();
RestRequest request = new RestRequest();

request.AddQueryParameter("client_id", "value");
request.AddQueryParameter("client_secret", "value");
request.AddQueryParameter("grant_type", "refresh_token");
request.AddQueryParameter("refresh_token", "value");

restClient.BaseUrl = new System.Uri("https://oauth2.googleapis.com/token");
restClient.Post(request);

https://youtu.be/aHs3edo0-mU

  • Thanks for this. It makes no sense to call for a refresh token using an async call. This is a cleaner approach, IMHO. One thing, you reference "RestClient " -- you are getting that from RestSharp that you got via nuget? – MarkJoel60 Feb 19 '21 at 19:53
  • @MarkJoel60, Yes I am using RestSharp which I installed via NuGet. – Purushotam Sah Feb 21 '21 at 14:09
3

POST /oauth2/v4/token

Host: www.googleapis.com

Headers

Content-length: 163

content-type: application/x-www-form-urlencoded

RequestBody

client_secret=************&grant_type=refresh_token&refresh_token=sasasdsa1312dsfsdf&client_id=************

Gaurav Bahl
  • 108
  • 1
  • 8
2

Using ASP.Net Post call, this worked for me.

StringBuilder getNewToken = new StringBuilder();
getNewToken.Append("https://www.googleapis.com/oauth2/v4/token");                        
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(getNewToken.ToString());
                    var values = new Dictionary<string, string>
                    {
                        { "client_id", <Your Client Id> },
                        { "client_secret", <Your Client Secret> },
                        { "refresh_token", <Your Saved Refresh Token> },
                        { "grant_type", "refresh_token"}
                    };

                    var content = new FormUrlEncodedContent(values);
                    var response = await client.PostAsync(getNewToken.ToString(), content);
1

As of 2023, google has updated the authentication and authorization mechanism. Now it is done using google identity service or gis. To use google apis gapi like drive, sheets etc, one has to go for authorization. And it has two flows.OAuth2

The key point to note is that for refresh token without user intervention and offline support, backend is must. Posting this as it might help in clarifying the two means..

abhay tripathi
  • 3,547
  • 4
  • 20
  • 25