如何在Python中使用刷新令牌Google API?

时间:2019-01-23 07:15:29

标签: python oauth google-api youtube-api google-oauth

此功能用于从Google获得经过身份验证的服务。之后

        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)

但是我想使用刷新令牌来自动进行身份验证,而无需打开浏览器。因此,在上面的函数中添加一些代码以保存刷新令牌:

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)

好的,那么在拥有刷新令牌后,如何使用它?我试图替换刷新令牌="ABCDEF456",但是它不起作用

def get_authenticated_service():
    return build(API_SERVICE_NAME, API_VERSION, credentials="ABCDEF456")

1 个答案:

答案 0 :(得分:0)

要刷新访问令牌,请调用Google OAuth端点,并传入三个参数:

  • 客户ID
  • 客户秘密
  • 刷新令牌

这可以通过简单的HTTP POST请求非常简单地完成。

以下是使用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://www.googleapis.com/oauth2/v4/token

在Python中使用请求库:

// 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://www.googleapis.com/oauth2/v4/token"

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

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

注意:如果最初在授权请求期间请求,则此代码还将返回刷新的ID令牌。