gpt4 book ai didi

python - 如何在Python中使用刷新 token Google API?

转载 作者:行者123 更新时间:2023-11-30 22:00:27 25 4
gpt4 key购买 nike

此函数用于从 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)

但我想使用刷新 token 自动进行身份验证,而无需打开浏览器。因此在上面的函数中添加一些代码来保存刷新 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)

好了,那么有了刷新 token 之后,如何使用呢?我尝试替换刷新 token ="ABCDEF456" 但它不起作用

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

最佳答案

要刷新访问 token ,您可以调用 Google OAuth 端点并传入三个参数:

  • 客户端 ID
  • 客户端 secret
  • 刷新 token

这可以通过简单的 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://oauth2.googleapis.com/token

在 Python 中使用 requests 库:

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

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

关于python - 如何在Python中使用刷新 token Google API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54321848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com