GCP身份验证:RefreshError

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

为了在我们的GCP后端中往返测试邮件发送代码,我正在向GMail收件箱发送电子邮件并尝试验证其到达。目前对GMail API进行身份验证的机制相当标准,从GMail API文档中粘贴并嵌入到函数中:

def authenticate():
    """Authenticates to the Gmail API using data in credentials.json,
    returning the service instance for use in queries etc."""
    store = file.Storage('token.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets(CRED_FILE_PATH, SCOPES)
        creds = tools.run_flow(flow, store)
    service = build('gmail', 'v1', http=creds.authorize(Http()))
    return service

CRED_FILE_PATH指向该服务的下载凭证文件。缺少token.json文件会在通过浏览器窗口进行身份验证交互后触发其重新创建,令牌的到期也是如此。

这是一个必须无头运行的集成测试(即没有任何交互)。当需要重新验证时,当验证流程开始访问sys.argv时,测试当前会引发异常,这意味着它会看到pytest的参数!

我一直试图找出如何使用不需要用户交互的机制(例如API密钥)可靠地进行身份验证。文档或Stackoverflow上的任何内容似乎都没有回答这个问题。

最近的一项努力使用来自具有GMail委派的服务帐户的密钥文件来避免交互式Oauth2流。

def authenticate():
    """Authenticates to the Gmail API using data in g_suite_access.json,
    returning the service instance for use in queries etc."""
    main_cred = service_account.Credentials.from_service_account_file(
        CRED_FILE_PATH, scopes=SCOPES)
    # Establish limited credential to minimise any damage.
    credentials = main_cred.with_subject(GMAIL_USER)
    service = build('gmail', 'v1', credentials=credentials)
    return service

试图使用此服务

        response = service.users().messages().list(userId='me',
                                    q=f'subject:{subject}').execute()

我明白了:

google.auth.exceptions.RefreshError:
  ('unauthorized_client: Client is unauthorized to retrieve access tokens using this method.',
   '{\n "error": "unauthorized_client",\n "error_description": "Client is unauthorized to retrieve access tokens using this method."\n}')

我感觉有一些根本我不理解的东西。

python authentication google-cloud-platform gmail authorization
1个回答
3
投票

服务帐户需要获得授权,或者无法访问域的电子邮件。

“客户端未经授权使用此方法检索访问令牌”

表示您未正确授权;检查Delegating domain-wide authority to the service account

资料来源:Client is unauthorized to retrieve access tokens using this method Gmail API C#

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