延长Google Oauth2的access_token的寿命

问题描述 投票:0回答:1

我正在使用以下代码来获取Google Oauth2服务的access_token。逻辑很简单。

  1. 执行代码
  2. 如果有令牌(保存在文件token.txt中,请使用它]
  3. 如果没有令牌,请使用基于浏览器的flow.run_console();将访问令牌保存到文件中
  4. 返回会话的build()

我的问题是,有没有办法将令牌的寿命延长到3600秒以上?像一个月?或更好?谢谢

代码:

def get_service(ServiceName, API_VERSION):
    flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
    creds = json.loads(Path(CLIENT_SECRETS_FILE).read_text())

    if Path(token).exists():
      access_token = Path(token).read_text()
      credentials = Credentials(
        None,
        refresh_token=access_token,
        token_uri="https://accounts.google.com/o/oauth2/token",
        client_id=creds['installed']['client_id'],
        client_secret=creds['installed']['client_secret']
      )
    else:
      credentials = flow.run_console()
      with open(token, 'w') as filetowrite:
            filetowrite.write(credentials.token)

    return build(ServiceName, API_VERSION, credentials = credentials)
python python-3.x google-api google-api-python-client
1个回答
0
投票

没有这是不可能的。很难证明不可能做到。但这是原因:

想法是,出于安全原因令牌是短暂的。人们应该获得一个额外的刷新令牌。 oauth令牌过期后,请使用刷新令牌来获取新的oauth令牌,或者最好使用新的令牌对。

这可降低窃听令牌的风险。即使攻击者设法获得令牌,它也只有很少的时间有效。如果服务提供商需要,还可以吊销特定令牌。

请参见OAuth2 and Google API: Access token expiration time?

© www.soinside.com 2019 - 2024. All rights reserved.