如何在 oauth 2.0 上自动使用刷新令牌获取访问令牌

How to get access tokens using refresh token automatically on oauth 2.0

正如你们所见,我是新来的。如果有任何问题,请指出我。

我在处理 oauth2.0 时遇到问题,特别是在获取访问令牌时遇到问题。

我现在正在使用此代码:

#esse bloco serve para criar o access_token, e vai atualizar o access_token sempre, retornando ele para o principal
    SCOPES = 'https://www.googleapis.com/auth/drive'
    creds = None
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # Esse bloco pode ser um problema para um server. É sempre preciso rodar esse bloco em um desktop para obter as chaves com autenticação.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
    # Salva as credenciais para uma proxima vez
    with open('token.json', 'w') as token:
        token.write(creds.to_json())
    a_file = open('token.json', "r")
    tokens = json.load(a_file)
    access_token = tokens['token']

这段代码有一些问题:

有没有办法自动完成(无需人工)?以及如何使用此更新访问令牌?

编辑:

由于有人指出,这里是 token.json

的通常结果
{"token": "*******", "refresh_token": "*****", "token_uri": "********", "client_id": "*********************", "client_secret": "****************", "scopes": "https://www.googleapis.com/auth/drive", "expiry": "2021-09-17T15:45:39Z"}

第一部分

When the first access token expires, it doesn't work anymore (so the token is not refreshed).

首先请检查 token.json 并验证是否存储了刷新令牌。或者你可以看看下面的代码。

def initialize_drive():
  """Initializes the drive service object.

  Returns:
    drive an authorized drive service object.
  """
  # Parse command-line arguments.
  parser = argparse.ArgumentParser(
      formatter_class=argparse.RawDescriptionHelpFormatter,
      parents=[tools.argparser])
  flags = parser.parse_args([])

  # Set up a Flow object to be used if we need to authenticate.
  flow = client.flow_from_clientsecrets(
      CLIENT_SECRETS_PATH, scope=SCOPES,
      message=tools.message_if_missing(CLIENT_SECRETS_PATH))

  # Prepare credentials, and authorize HTTP object with them.
  # If the credentials don't exist or are invalid run through the native client
  # flow. The Storage object will ensure that if successful the good
  # credentials will get written back to a file.
  storage = file.Storage('drive.dat')
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow, storage, flags)
  http = credentials.authorize(http=httplib2.Http())

  # Build the service object.
  drive = build('drive', 'v3', http=http)

  return drive

第二部分

Is there a way to do it automatically (without the need for a human) ? And how do I update access token using this ?

是的,您可以使用服务帐户。服务帐户就像虚拟用户。服务帐户有自己的 google 驱动器帐户,因此您可以从中上传和下载。您还可以像任何其他用户一样与服务帐户共享您的个人驱动器帐户上的目录。然后服务帐户将有权从中上传和下载。由于它是预授权的,因此无需用户同意其访问。

注意:服务帐户只能用于开发者拥有的驱动器帐户。如果您正在访问您的用户驱动器帐户,那么您应该使用 Oauth2。

def initialize_drive():
  """Initializes an drive API V3 service object.

  Returns:
    An authorized Google Drive API V3 service object.
  """
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      KEY_FILE_LOCATION, SCOPES)

  # Build the service object.
  drive = build('drive', 'v3', credentials=credentials)

  return analytics

链接