我想用服务帐号处理 Google Work Space Group 邮件,但身份验证不起作用

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

我想解决的问题

我想通过服务帐户操作我公司的 Google Work Space Group 电子邮件,但身份验证不起作用。 我收到 HttpError 400 错误,我觉得我没有足够的身份验证信息或授权,但我无法确定原因。由于我公司使用的是GCP,无法多次申请授权,所以想在一定程度上缩小原因和解决方法,希望大家多多指教。 我想在一定程度上缩小原因和解决方案,所以我想得到你的建议。

我们最终想做的是:**我们想用一个服务账号来处理Gmail。 ** 就这些了

提前谢谢你。

  • 编辑器
  • 服务帐号管理员

我自己试过的

  • 激活Gmailapi,确认。
  • 已通过用户帐户验证 -> 已成功检索 Gmail,确认。

服务账号密钥json文件如下。 (部分内容已改写)

www.DeepL.com/Translator翻译(免费版)

{
  "type": "service_account",
  "project_id": “my-project”,
  "private_key_id": “12345678xxxxxxxxxxxx”,
  "private_key": "-----BEGIN PRIVATE KEY-----\nxxxxxxxxxxxxxxxxxxxxxxxx=\n-----END PRIVATE KEY-----\n",
  "client_email": “[email protected]",
  "client_id": “12345678901234567890”,
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/my-project%40vmy-project.iam.gserviceaccount.com"
}

这是正在执行的python代码。 例如,可以通过使用下面注释掉的 1.User Account Ver 运行它来检索电子邮件。

from pprint import pprint
from googleapiclient.errors import HttpError
from googleapiclient.discovery import build
from google.oauth2.service_account import Credentials
# from google.oauth2.credentials import Credentials #User Account Vertion

MAXRESULT= 100
SCOPE    = ['https://www.googleapis.com/auth/gmail.readonly']
user_key = '../user_token.json'
sa_key   = '../service_account_token.json'
query    = "[email protected]"

### 1.User Account Vertion----------
# creds = Credentials.from_authorized_user_file(user_key, SCOPE)

### 2.Service Account Vertion ----------
creds = Credentials.from_service_account_file(sa_key, scopes=SCOPE)

try:
    # Call the Gmail API
    service = build('gmail', 'v1', credentials=creds)
    results = service.users().labels().list(userId='me').execute()
    labels = results.get('labels', [])
    # Token Verification
    print("cred.token: {}\ncreds.valid: {}".format(creds.token, creds.valid))

    if not labels:
        print('No labels found.')

    ### Get mail list
    messageIDlist = service.users().messages().list(userId="me", maxResults=MAXRESULT, q=query).execute()
    mes = messageIDlist["messages"]
    print("mes_id:{}".format(mes[0]['id']))
    pprint(service.users().messages().get(userId="me", id=mes[0]['id']).execute())

except HttpError as error:
    # TODO(developer) - Handle errors from gmail API.
    print(f'An error occurred: {error}')

出现问题/错误

An error occurred: <HttpError 400 when requesting https://gmail.googleapis.com/gmail/v1/users/me/labels?alt=json returned "Precondition check failed.". Details: "[{'message': 'Precondition check failed.', 'domain': 'global', 'reason': 'failedPrecondition'}]">

“https://gmail.googleapis.com/gmail/v1/users/me/labels?alt=json” 当我打开网址时,我收到这条消息。

{
  "error": {
    "code": 401,
    "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "errors": [
      {
        "message": "Login Required.",
        "domain": "global",
        "reason": "required",
        "location": "Authorization",
        "locationType": "header"
      }
    ],
    "status": "UNAUTHENTICATED",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.ErrorInfo",
        "reason": "CREDENTIALS_MISSING",
        "domain": "googleapis.com",
        "metadata": {
          "method": "caribou.api.proto.MailboxService.ListLabels",
          "service": "gmail.googleapis.com"
        }
      }
    ]
  }
}

请评论您需要的任何其他信息,我会添加它。 提前谢谢你。

python google-cloud-platform oauth gmail gmail-api
1个回答
0
投票

要在 Gmail 中使用服务帐户,您必须委托给您域中的用户

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE_PATH,
    scopes=SCOPES)

credentials = credentials.create_delegated(user_email)

如果不委托给域上的用户,您将收到

"Precondition check failed."
错误,因为服务帐户本身没有 gmail 帐户。

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