How to generate access token using refresh token through google drive API?
Asked Answered
O

13

95

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.

Overdye answered 17/5, 2012 at 6:42 Comment(0)
V
34

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

Vagal answered 17/5, 2012 at 16:17 Comment(3)
The documents you mentioned are dealing with only Raw-HTTP communication. Is there any method in PHP-API for refreshing tokens?Plethoric
@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 iOSWashcloth
I dont wanted to imlement it myself. can somebody provide a sample code using google apis?Chopin
A
68

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"
}
Assort answered 16/7, 2016 at 18:20 Comment(7)
working pragmatically with httpclient, not working from postman in may case as well.Maddox
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 : #48776259Music
where do you get the client_secret from and the refresh token?Verve
this is not working for me. it says unauthorized and invalid clientBellybutton
the client_secrets and client_id can be obtained from the Google Developers console, in the credentials tab of your project. Open console.developers.google.com/apis/dashboardDrier
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" ] );Rene
If refresh token never expires, why is there a "expires_id" field? P.s my refresh token is expiring after every hour.Landlady
V
34

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

Vagal answered 17/5, 2012 at 16:17 Comment(3)
The documents you mentioned are dealing with only Raw-HTTP communication. Is there any method in PHP-API for refreshing tokens?Plethoric
@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 iOSWashcloth
I dont wanted to imlement it myself. can somebody provide a sample code using google apis?Chopin
D
34

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 :-)

Dogbane answered 26/9, 2015 at 16:35 Comment(6)
How do you actually get a access token to begin with?Verve
Google Cloud PlatformDogbane
but this access token not expire after 3600 ? so i not need to reauthenticate my users ?Woodrowwoodruff
highlight text: the access token with the refresh token only in the first authorizationLegalese
Thanks @While1, I followed your suggestion :-)Dogbane
It is worth mentioning that refresh token can be requested not only for the first time, although it is not written in the official documentation D: Information can be found here: github.com/googleapis/google-api-python-client/issues/213Algorism
R
16

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"
}
Revareval answered 1/9, 2019 at 7:37 Comment(0)
E
7

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.

Encumbrance answered 24/7, 2018 at 12:11 Comment(1)
Perfect explanation. Should be the accepted answer.Stunner
V
7

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

Vender answered 1/2, 2021 at 17:59 Comment(2)
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?Rameriz
@MarkJoel60, Yes I am using RestSharp which I installed via NuGet.Vender
T
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();
Talmud answered 17/12, 2018 at 10:32 Comment(1)
please mention : yourOldToken is actually the refresh tokenManiacal
M
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=************

Michi answered 28/6, 2018 at 20:3 Comment(0)
D
3

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..

Domesticate answered 28/1, 2023 at 15:5 Comment(2)
What do you mean by Backend is must ?Stacystadholder
I guess is that e.g. for mobile applications, developer must provide it's own backend service used to prolong google access tokenEquitant
K
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);
Kevel answered 15/7, 2019 at 11:58 Comment(0)
M
2

Using curl:

curl -d "client_id=CLIENT_ID" \
 -d "client_secret=CLIENT_SECRET" \
 -d "refresh_token=REFRESH_TOKEN" \
 -d "grant_type=refresh_token" \
 https://oauth2.googleapis.com/token

Run this from command line or call using program. You are supposed to get a response like:

{
  "access_token": "ya29....1",
  "expires_in": 3599,
  "scope": "https://www.googleapis.com/auth/drive",
  "token_type": "Bearer",
  "id_token": "ey...bg"
}

Now you can parse the response and get new access_token.

This new access_token expires after 3599 sec = 1 hour. After that you have to generate another access_token.

Using Java:

Let's write a method: (refurbished code of @Divyesh Kanzariya)

public  String generateAccessToken() throws IOException {
    String refreshToken = "your refresh token";
    
    HttpTransport httpTransport;
    JsonFactory JSON_FACTORY;
    try {
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        JSON_FACTORY = JacksonFactory.getDefaultInstance();
    } catch (Exception e) {
        throw new IOException("Error initializing HTTP transport", e);
    }

    // Create TokenResponse from the provided refresh token
    TokenResponse tokenResponse = new TokenResponse();
    tokenResponse.setRefreshToken(refreshToken);


    GoogleCredential credential = new GoogleCredential.Builder()
            .setJsonFactory(JSON_FACTORY)
            .setTransport(httpTransport)
            .setClientSecrets("your ClientId", "your ClientSecret")
            .build()
            .setRefreshToken(refreshToken);
    credential.refreshToken(); //do not forget to call this



    try {
        // Check if the credential is still valid
        if (credential.getExpiresInSeconds() == null || credential.getExpiresInSeconds() > 60) {
            return credential.getAccessToken();
        } else {
            throw new IOException("Provided refresh token is invalid or has expired.");
        }
    } catch (Exception e) {
        throw new IOException("Error obtaining access token", e);
    }
}
Maniacal answered 13/1, 2024 at 19:40 Comment(0)
R
1

It is not obvious where to find Google documentation/reference for REST API for obtaining an access token based on a refresh token. It seems this is the current link (as 2024):

https://developers.google.com/identity/protocols/oauth2/native-app?hl=en#offline

The URL is https://oauth2.googleapis.com/token however one should not hardcode this, but use value of "token_uri" attribute from the Google secrets file that can be obtain from Google Cloud Console.

Raskin answered 2/2, 2024 at 22:15 Comment(0)
S
0

I'm using the Nodejs library for a personal project accessing my Gmail account. I just needed to delete the token (in token.json) then rerun the app, and that triggered the login flow again to get a code and generate another token file.

Simplicidentate answered 29/7, 2024 at 19:37 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.