我正在使用Google Application Default Credentials来使用Gmail API获取标签列表。
使用gcloud preview app run
命令在本地运行应用程序时,我收到HttpError: <HttpError 403 when requesting https://www.googleapis.com/gmail/v1/users/user%40domain.com/labels?alt=json returned "Insufficient Permission">
然后我部署了应用程序并尝试访问。但我得到了HttpError: <HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/user%40domain.com/labels?alt=json returned "Bad Request">
我在gcloud config list
中有正确的配置:
account = my_email@domain.com (Appengine Application Owener & Domain Admin)
disable_usage_reporting = False
project = <appengine_project_id>
gcloud版本详情:
Google Cloud SDK 0.9.76
app 2015.08.27
app-engine-python 1.9.25
bq 2.0.18
bq-nix 2.0.18
core 2015.08.27
core-nix 2015.06.02
gcloud 2015.08.27
gsutil 4.14
gsutil-nix 4.12
preview 2015.08.27
此外,我添加了服务帐户的客户端ID&amp; Gmail范围:Google帐户管理员中的https://www.googleapis.com/auth/gmail.readonly以及在Appengine控制台中启用的Gmail API。
以下是代码:
from googleapiclient.discovery import build
from oauth2client.client import GoogleCredentials
class Connection:
def __init__(cls):
cls.credentials = GoogleCredentials.get_application_default()
def fetch_labels(cls):
service = build('gmail', 'v1', credentials=cls.credentials)
logging.info(service)
results = service.users().labels().list(userId='user@domain.com').execute()
labels = results.get('labels', [])
if not labels:
logging.info('No labels found.')
else:
logging.info('Labels:')
for label in labels:
logging.info(label['name'])
pass
class Handler(webapp2.RequestHandler):
def get(self):
con = Connection()
con.fetch_labels()
答案 0 :(得分:1)
我对此并不是100%肯定,但我认为Application Default Credentials不支持域范围的授权。您仍然需要使用带有sub
参数的服务帐户凭据:
credentials = SignedJwtAssertionCredentials(
service_account_email, service_account_key,
scope='...', sub=user_email)