Refresh Google drive access__token

You can use refresh token. The access token can be updated by the refresh token. This refresh token can be retrieved as follows. At first, following information is required for retrieving refreshtoken.

  • Client ID
  • Client Secret
  • Redirect URI
  • Scopes

From your question, it seems that you already have an accesstoken. So I think that you have above information.

Next, using above information, it retrieves Authorization Code that your application can use to obtain the access token. Please make an URL as follows and put it to your browser, and authorize by click. I always retrieve the code using this URL and retrieve the refresh token. The refresh token can be retrieved by including access_type=offline.

https://accounts.google.com/o/oauth2/auth?
response_type=code&
approval_prompt=force&
access_type=offline&
client_id=### your_client_ID ###&
redirect_uri=### edirect_uri ###&
scope=### scopes ###

Authorization Code is shown on browser or as an URL. You can retrieve the refresh token using the code.

Following 2 samples are python scripts.

Retrieves refresh token :

import requests
r = requests.post(
    'https://accounts.google.com/o/oauth2/token',
    headers={'content-type': 'application/x-www-form-urlencoded'},
    data={
        'grant_type': 'authorization_code',
        'client_id': '#####',
        'client_secret': '#####',
        'redirect_uri': '#####',
        'code': '#####',
    }
)

Retrieves access token using refresh token :

import requests
r = requests.post(
    'https://www.googleapis.com/oauth2/v4/token',
    headers={'content-type': 'application/x-www-form-urlencoded'},
    data={
        'grant_type': 'refresh_token',
        'client_id': '#####',
        'client_secret': '#####',
        'refresh_token': '#####',
    }
)

You can see the detail infomation here. https://developers.google.com/identity/protocols/OAuth2WebServer

Leave a Comment