Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Refresh Token Google API in Python? [duplicate]

This function is to get authenticated service from Google. After

        API_SERVICE_NAME = 'youtubereporting'
        API_VERSION = 'v1'
        CLIENT_SECRETS_FILE = "client_secret_929791903032-hpdm8djidqd8o5nqg2gk66efau34ea6q.apps.googleusercontent.com.json"
        SCOPES = ['https://www.googleapis.com/auth/yt-analytics-monetary.readonly']
        def get_authenticated_service():
            flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
            credentials = flow.run_local_server()
            return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)

But I want to use Refresh Token to automatically authenticate without opening a browser. Therefore add some codes into the function above to save Refresh Token:

def get_authenticated_service():
    flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
    credentials = flow.run_local_server()
    with open('refresh.token', 'w+') as f:
        f.write(credentials._refresh_token)
    print('Refresh Token:', credentials._refresh_token)
    print('Saved Refresh Token to file: refresh.token')
    return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)

Okay, so after having the Refresh Token, How to use it? I tried to replace the refresh token ="ABCDEF456" but it does not work

def get_authenticated_service():
    return build(API_SERVICE_NAME, API_VERSION, credentials="ABCDEF456")
like image 651
Analytics POPSWW Avatar asked Jan 23 '19 07:01

Analytics POPSWW


People also ask

How do you refresh an access token in Python?

The aim for this is to have the script send out a request for a refresh of the token by inputting the Client ID, Client Secret, and Refresh Token (found in the access_token. json file) into the URL, sending the request, and putting the data it receives back into the access_token. json file.

Can I use refresh token multiple times?

So the answer is, Yes you can (and probably should) wait until your access token expires, and then refresh it.

How do I get new token with refresh token?

To get an access token using a refresh token, you must first get the refresh token. Then you use the refresh token from then on to generate an access token.


1 Answers

To refresh an Access Token, you call the Google OAuth endpoint passing in three parameters:

  • Client ID
  • Client Secret
  • Refresh Token

This can be done very simply with a simple HTTP POST request.

Here is an example using curl:

set REFRESH_TOKEN=REPLACE_WITH_REFRESH_TOKEN
 
curl ^
--data client_id=%CLIENT_ID% ^
--data client_secret=%CLIENT_SECRET% ^
--data grant_type=refresh_token ^
--data refresh_token=%REFRESH_TOKEN% ^
https://oauth2.googleapis.com/token

In Python using the requests library:

// Call refreshToken which creates a new Access Token
access_token = refreshToken(client_id, client_secret, refresh_token)

// Pass the new Access Token to Credentials() to create new credentials
credentials = google.oauth2.credentials.Credentials(access_token)

// This function creates a new Access Token using the Refresh Token
// and also refreshes the ID Token (see comment below).
def refreshToken(client_id, client_secret, refresh_token):
        params = {
                "grant_type": "refresh_token",
                "client_id": client_id,
                "client_secret": client_secret,
                "refresh_token": refresh_token
        }

        authorization_url = "https://oauth2.googleapis.com/token"

        r = requests.post(authorization_url, data=params)

        if r.ok:
                return r.json()['access_token']
        else:
                return None

Note: This code will also return a refreshed ID Token if originally requested during the authorization request.

like image 125
John Hanley Avatar answered Nov 03 '22 00:11

John Hanley