谷歌 OAuth 刷新令牌不断过期

时间:2021-07-23 11:35:38

标签: python google-oauth


我无法让我的 google OAuth 刷新令牌对我正在编写的小型应用程序有效。我需要将数据从电子表格获取到服务器/桌面应用程序。 我正在尝试使用 OAuth 进行授权,它可以工作一周,然后停止。
根据这篇文章,这是预期的行为:
https://stackoverflow.com/a/67966982/16509954
同一线程中的另一个答案发布了如何永久授予访问权限而不使您的令牌过期的方法: https://stackoverflow.com/a/66292541/16509954
我这样做了,但我的令牌仍然会过期。 知道我做错了什么吗?

我正在使用 python 库,我的代码与文档 quickstart.py 中给出的示例几乎相同:
https://developers.google.com/sheets/api/quickstart/python

1 个答案:

答案 0 :(得分:0)

刷新令牌可能会因多种原因而过期,目前最主要的原因是您的应用程序仍处于测试阶段。

enter image description here

在 Google 云控制台中将您的应用程序设置为生产并对其进行验证,刷新令牌不会在一周后过期。

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials


SCOPES = ['https://www.googleapis.com/auth/drive.drive']
KEY_FILE_LOCATION = '<REPLACE_WITH_JSON_FILE>'
VIEW_ID = '<REPLACE_WITH_VIEW_ID>'


def initialize_sheets():
  """Initializes an sheets service object.

  Returns:
    An authorized sheets  service object.
  """
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      KEY_FILE_LOCATION, SCOPES)

  # Build the service object.
  service = build('sheets', 'v4', credentials=creds)

  return service