Google Cloud API:禁止使用服务帐户密钥访问启用的API

时间:2016-01-28 20:52:01

标签: google-cloud-platform google-api-python-client

我遇到问题时使用服务帐户P12键并获取 HttpError 403

但是,如果我使用客户端ID和密钥使用Web OAuth,则不会出现此问题。但是,我正在创建服务到服务应用程序。

已启用Google Cloud API JSON

import os
from httplib2 import Http
from pprintpp import pprint

from oauth2client.client import SignedJwtAssertionCredentials
from apiclient.discovery import build
from googleapiclient.errors import HttpError

SITE_ROOT = \
    os.path.dirname(os.path.realpath(__file__))
P12_FILE = \
    "REDACTED-0123456789.p12"

P12_PATH = os.path.join(SITE_ROOT, P12_FILE)
pprint(P12_PATH)

SCOPE = \
    'https://www.googleapis.com/auth/devstorage.read_only'
PROJECT_NAME = \
    'mobileapptracking-insights'
BUCKET_NAME = \
    'pubsite_prod_rev_0123456789'
CLIENT_EMAIL = \
    'REDACTED-service@foo-bar-0123456789.iam.gserviceaccount.com'

private_key = None
with open(P12_PATH, "rb") as p12_fp:
  private_key = p12_fp.read()

credentials = SignedJwtAssertionCredentials(
    CLIENT_EMAIL,
    private_key,
    SCOPE)

http_auth = credentials.authorize(Http())

storage = build('storage', version='v1', http=http_auth)

request = storage.objects().list(bucket=BUCKET_NAME)

try:
    response = request.execute()
except HttpError as error:
    print("HttpError: %s" % str(error))
    raise
except Exception as error:
    print("%s: %s" % (error.__class__.__name__, str(error)))
    raise

print(response)

错误讯息:

HttpError: <HttpError 403 when requesting https://www.googleapis.com/storage/v1/b/pubsite_prod_rev_0123456789/o?alt=json returned "Forbidden">

我需要做些什么才能解决此问题?

2 个答案:

答案 0 :(得分:1)

您的代码看起来很好(我只是粘贴它,更改了相应的常量,并成功运行了它)。

我会仔细检查:

  • 您的客户电子邮件是正确的p12键
  • 您列出的广告资源可供该服务帐户访问

您可以采取其他一些措施来帮助您找出问题所在:

  • 确认您可以列出公开uspto-pair广告文件
  • import httplib2并设置httplib2.debuglevel = 1,并验证正在发出的请求是否为预期请求。

答案 1 :(得分:0)

问题在于我没有为服务的客户电子邮件分配访问权限&#39;通过 Google Play开发者控制台&gt;设置&gt;用户帐户&amp;权利