在google pubsub中设置gmail的发布权限,拒绝权限

时间:2016-05-08 17:19:46

标签: php google-api gmail-api google-cloud-pubsub

我正在尝试将gmail的发布权限设置为google云中的pubsub主题。 我实现此代码的应用程序在AWS中运行。 这是一个PHP应用程序,我使用的是谷歌PHP api客户端的2.0.0-RC7版本。

在代码中,我按照文档中的描述实现了流程:

  • 创建主题(Works)
  • 创建订阅(有效)
  • 授予gmail发布权限(此处我遇到困难)

前两个操作是使用相同的Google客户端实例完成的,该实例使用服务帐户凭据进行身份验证。

代码:

$scopes = [
    'https://www.googleapis.com/auth/pubsub',
    'https://mail.google.com',
];
$pushEndpoint = 'https://some.url/google_notifications/';

$client = new Google_Client();
$client->setScopes($scopes);
$client->setAuthConfig($serviceAccountInfo);
if ($client->isAccessTokenExpired()) {
    $client->refreshTokenWithAssertion();
}
$service = new Google_Service_Pubsub($client);

// This part works
$topicObject = new Google_Service_Pubsub_Topic();
$topicObject->setName($this->getTopicName());
$service->projects_topics->create($this->getTopicName(), $topic);

// This part also works
$push = new Google_Service_Pubsub_PushConfig();
$push->setPushEndpoint($pushEndpoint);

$subscription = new Google_Service_Pubsub_Subscription();
$subscription->setName($this->getSubscriptionName());
$subscription->setTopic($this->getTopicName());
$subscription->setPushConfig($push);
$service->projects_subscriptions->create($this->getSubscriptionName(), $subscription);

// This part gives the error
$binding = new Google_Service_Pubsub_Binding();
$binding->setRole('roles/pubsub.publisher');
$binding->setMembers(['serviceAccount:gmail-api-push@system.gserviceaccount.com']);

$policy = new Google_Service_Pubsub_Policy();
$policy->setBindings([$binding]);

$setRequest = new Google_Service_Pubsub_SetIamPolicyRequest();
$setRequest->setPolicy($policy);

try {
    $result = $service->projects_topics->setIamPolicy($this->getTopicName(), $setRequest);
    var_dump($result);
} catch (\Exception $e) {
    echo $e->getMessage();
}

结果总是:

{
  "error": {
    "code": 403,
    "message": "User not authorized to perform this action.",
    "errors": [
      {
        "message": "User not authorized to perform this action.",
        "domain": "global",
        "reason": "forbidden"
      }
    ],
    "status": "PERMISSION_DENIED"
  }
}

有人可以告诉我我做错了什么吗? 手动设置这些权限真的很烦人。

感谢。

1 个答案:

答案 0 :(得分:0)

要使用projects.topics.setIamPolicy方法,您的服务帐户必须具有“发布/订阅管理员”角色。您可以通过访问项目的“ IAM和管理员”页面来更改帐户的角色:https://console.cloud.google.com/iam-admin/iam

相关问题