【问题标题】:Google Cloud Platform API Creating Service Accounts by a Service account (PHP)Google Cloud Platform API 通过服务帐户创建服务帐户 (PHP)
【发布时间】:2022-11-08 22:21:00
【问题描述】:

我正在尝试使用服务帐户在项目上创建服务帐户,但我无法让它工作。现在,我只是简单地尝试使用许可的服务帐户列出项目中的所有服务帐户,但它返回 401 错误。这甚至可能与服务帐户有关吗?

    $sa = new ServiceAccountCredentials([
        'iam.serviceAccounts.list'
    ], base_path() . '/credentials.json');

    $middleware = new AuthTokenMiddleware($sa);
    $stack = HandlerStack::create();
    $stack->push($middleware);

    // create the HTTP client
    $client = new Client([
        'handler' => $stack,
        'base_uri' => 'https://iam.googleapis.com',
        'auth' => 'google_auth'  // authorize all requests
    ]);

    $response = $client->get('v1/projects/project-id-1/serviceAccounts');
    var_dump((String) $response->getBody());

回复:

{
  "error": {
    "code": 401,
    "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED"
  }
}

编辑: 我的包裹:

"google/auth": "^1.19",
"guzzlehttp/guzzle": "^7.0.1"

【问题讨论】:

标签: php google-cloud-platform google-oauth google-api-php-client


【解决方案1】:

你的代码的第二行'iam.serviceAccounts.list'是不正确的。您正在指定 IAM 权限。该方法需要一个范围.

此方法请参阅documentation

$sa = new ServiceAccountCredentials([
    'https://www.googleapis.com/auth/cloud-platform'
], base_path() . '/credentials.json');

使用您的第二个参数,当调用该方法时,将执行请求范围的查找。由于您没有指定有效范围,因此最终结果是您拥有一个凭证没有权限.这会导致错误消息:

Request had invalid authentication credentials. Expected OAuth 2 access token ...

使用服务帐户时不要通过范围控制权限。使用 IAM 角色定义服务账户拥有的权限。然后使用云平台范围。

我写了一篇关于 Google Cloud 凭据和 PHP 的文章,可能有助于提供详细信息:

Google Cloud Application Default Credentials – PHP

【讨论】:

    猜你喜欢
    • 2020-07-11
    • 2021-09-30
    • 2018-02-18
    • 2021-09-05
    • 2015-06-12
    • 1970-01-01
    • 2019-07-25
    • 2021-12-19
    相关资源
    最近更新 更多