请求令牌时,Google API 刷新令牌为无
Posted
技术标签:
【中文标题】请求令牌时,Google API 刷新令牌为无【英文标题】:Google API refresh token is None when requesting tokens 【发布时间】:2020-11-04 08:40:30 【问题描述】:我已按照以下指南为我的应用程序获取 Google Ads API 刷新令牌。
https://github.com/googleads/googleads-python-lib/wiki/API-access-on-behalf-of-your-clients-(web-flow)
使用下面的脚本,一切正常,但响应只有一个访问令牌,而刷新令牌是无。
from googleads import oauth2
import google.oauth2.credentials
import google_auth_oauthlib.flow
# Initialize the flow using the client ID and secret downloaded earlier.
# Note: You can use the GetAPIScope helper function to retrieve the
# appropriate scope for AdWords or Ad Manager.
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
'client_secret.json',
[oauth2.GetAPIScope('adwords')])
# Indicate where the API server will redirect the user after the user completes
# the authorization flow. The redirect URI is required.
flow.redirect_uri = 'https://www.example.com'
# Generate URL for request to Google's OAuth 2.0 server.
# Use kwargs to set optional request parameters.
authorization_url, state = flow.authorization_url(
# Enable offline access so that you can refresh an access token without
# re-prompting the user for permission. Recommended for web server apps.
access_type='offline',
# Enable incremental authorization. Recommended as a best practice.
include_granted_scopes='true',
# approval_prompt='force'
)
print("\n" + authorization_url)
print("\nVisit the above URL and grant access. You will be redirected. Get the 'code' from the query params of the redirect URL.")
auth_code = input('\nCode: ').strip()
flow.fetch_token(code=auth_code)
credentials = flow.credentials
print(credentials.__dict__)
【问题讨论】:
【参考方案1】:问题似乎是我之前已经完成了这些步骤。
解决方案是将approval_prompt='force'
包含在flow.authorization_url()
中。以这种方式生成authorization_url
后,响应中还包含一个刷新令牌。
【讨论】:
为我工作!非常感谢以上是关于请求令牌时,Google API 刷新令牌为无的主要内容,如果未能解决你的问题,请参考以下文章
如何从 Google Calendar API 获取刷新的令牌
如何从 Google YouTube Data API OAuth 2 iOS 获取刷新令牌
使用过期令牌发出同时 API 请求时如何避免多个令牌刷新请求