gmail api watch:未经授权,客户端无法使用此方法检索访问令牌,或者未经授权的客户端无法访问任何请求的范围

时间:2020-01-13 23:06:00

标签: gmail-api

我正在尝试从python谷歌云函数调用User: watch

我正在笔记本电脑上测试脚本。

我所做的设置:

  1. 在项目上启用gmail API
  2. 使用json凭证文件创建服务帐户
  3. 使用以下API范围['https://mail.google.com/','https://www.googleapis.com/auth/admin.directory.user']将服务帐户的客户ID放入Manage API client access
  4. 确认已启用G Suite域范围委派

我一直收到的错误是: err=('unauthorized_client: Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.', '{\n "error": "unauthorized_client",\n "error_description": "Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested."\n}')

我尝试传递服务凭证帐户并设置userId = TARGET_INBOX,但这只是一个错误的请求。我尝试查看与此错误相关的其他SO帖子,但看不到我做错了什么。

Pipfile:

[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true

[dev-packages]
pytest = "*"

[packages]
flask = "*"
google-cloud-pubsub = "*"
google-api-python-client = "*"
google-auth = "*"

[requires]
python_version = "3.7"

watch_inboxes.py

import os

import google.auth
from google.auth import impersonated_credentials
from google.auth.exceptions import RefreshError
from googleapiclient.discovery import build
import json

from googleapiclient.errors import HttpError

SCOPES = ['https://mail.google.com/', 'https://www.googleapis.com/auth/admin.directory.user']

TARGET_INBOX = '***TARGET_EMAIL_ADDRESS****'


def watch_inboxes(request):

    if not os.environ['GOOGLE_APPLICATION_CREDENTIALS']:
        exit(-1)

    creds, proj = google.auth.default()

    request = {
        'labelIds': ['INBOX'],
        'topicName': 'projects/***PROJECTNAME***/topics/***TOPICNAME****'
    }

    delegated_credentials = creds.with_subject(TARGET_INBOX)

    org_service = build('gmail', 'v1', credentials=delegated_credentials)
    org_rval = None

    try:
        org_rval = org_service.users().watch(userId='me', body=request).execute()
    except HttpError as err:
        print("err={}, context={}".format(err, err.content))
    except RefreshError as err:
        print("err={}".format(err))

    print("org_rval={}".format(org_rval))

    return org_rval

1 个答案:

答案 0 :(得分:2)

在阅读代码后,您似乎忘记了将scopes添加到google.auth.default()-function中。

所以最终产品看起来像这样google.auth.default(scopes)

相关问题