【问题标题】:Google OAuth2 refresh expires & does not renewGoogle OAuth2 刷新过期且不会续订
【发布时间】:2019-11-12 22:25:35
【问题描述】:

我完全关注this tutorial,但是

@app.route('/test')
def test_api_request():
  if 'credentials' not in flask.session:
    return flask.redirect('authorize')

  # Load credentials from the session.
  credentials = google.oauth2.credentials.Credentials(
      **flask.session['credentials'])

  drive = googleapiclient.discovery.build(
      API_SERVICE_NAME, API_VERSION, credentials=credentials)

  files = drive.files().list().execute()

  # Save credentials back to session in case access token was refreshed.
  # ACTION ITEM: In a production app, you likely want to save these
  #              credentials in a persistent database instead.
  flask.session['credentials'] = credentials_to_dict(credentials)

  return flask.jsonify(**files)

但是在这部分:

  credentials = google.oauth2.credentials.Credentials(
      **flask.session['credentials'])

刷新令牌在一小时后过期,出现以下错误:

The credentials do not contain the necessary fields need to refresh the access token. You must specify refresh_token, token_uri, client_id, and client_secret.

但显然在烧瓶会话中 dict 对象在那里:

{'client_id': '<COMMENTED_OUT>.apps.googleusercontent.com',
 'client_secret': '<COMMENTED_OUT>',
 'refresh_token': None,
 'scopes': ['https://spreadsheets.google.com/feeds',
            'https://www.googleapis.com/auth/drive',
            'https://mail.google.com/'],
 'token': '<COMMENTED_OUT>',
 'token_uri': 'https://oauth2.googleapis.com/token'}

我相信谷歌教程会自动刷新令牌

两个问题 1)我需要手动“刷新”刷新令牌吗?教程中的评论说“将凭据保存回会话以防刷新访问令牌”..这意味着它会自动刷新

2) 这是因为该应用仍处于未验证状态吗?

【问题讨论】:

    标签: oauth oauth-2.0 google-oauth


    【解决方案1】:

    查看dict,缺少刷新令牌:

    'refresh_token': None,
    

    您需要此令牌才能在访问令牌过期后刷新它。仅当用户看到同意屏幕(列出所请求范围的屏幕)时,才会在 JSON 响应中提供刷新令牌。如果用户之前已批准访问,并且范围未更改,则 OAuth 流程将在用户被送回流程时跳过该屏幕,因此不会返回刷新令牌。

    可能发生的情况是,在您的测试期间,您批准了一次访问,但没有正确存储刷新令牌。进一步尝试批准访问没有返回刷新令牌,因此您无法刷新访问令牌。

    为确保始终返回刷新令牌,请在授权 URL 中设置 URL 参数 prompt=consent

    authorization_url, state = flow.authorization_url(
        access_type='offline',
        include_granted_scopes='true'
        prompt='consent')
    

    (记录在“HTTP/REST”标签here中)。

    或者,visit 并撤销对您的应用程序的访问权限。下次您通过 OAuth 流程时,您应该会再次看到同意屏幕,并获得一个新的刷新令牌。

    【讨论】:

      猜你喜欢
      • 2018-04-07
      • 1970-01-01
      • 2012-02-15
      • 2017-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-09
      • 2016-08-03
      相关资源
      最近更新 更多