GCP 身份验证:刷新错误



为了在我们的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}')

我感觉有一些我不理解的基本内容。

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

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

表示您未正确授权;请选中将全网域权限委派给服务帐号

来源:客户端未经授权使用此方法检索访问令牌 Gmail API C#

最新更新