php - 使用服务帐户的 Google Cloud API PHP 客户端身份验证
问题描述
我正在处理一个使用 PHP 的项目,需要使用 PHP 客户端库实现 Google Cloud API,但身份验证似乎对我不起作用。我创建了一个服务帐户并授予项目所有者权限,我不想使用 GOOGLE_DEFAULT_CREDENTIALS 环境变量进行身份验证,我想使用服务帐户身份验证。
这是我尝试过的:
require 'vendor/autoload.php';
use Google\Cloud\Core\ServiceBuilder;
use Google\Cloud\Storage\StorageClient;
// Authentication with Google Cloud Platform
$client = new ServiceBuilder([
'keyFilePath' => 'api-project-374381085870-eaf930d9ffd7.json'
]);
$client = new StorageClient();
$bucket = $client->bucket('storage_client');
// Upload a file to the bucket.
$bucket->upload(
fopen('file.txt', 'r')
);
但它返回一个错误:
警告:file_get_contents(/Users/abdul/.config/gcloud/application_default_credentials.json):无法打开流:/Applications/XAMPP/xamppfiles/htdocs/storage/vendor/google/auth/src/CredentialsLoader.php 中的权限被拒绝第 102 行
警告:file_get_contents(/Users/abdul/.config/gcloud/application_default_credentials.json):无法打开流:/Applications/XAMPP/xamppfiles/htdocs/storage/vendor/google/auth/src/CredentialsLoader.php 中的权限被拒绝第 102 行
致命错误:未捕获的异常 'Google\Cloud\Core\Exception\ServiceException' 带有消息 '{ "error": { "errors": [ { "domain": "global", "reason": "authError", "message" : "Invalid Credentials", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Invalid Credentials" } ' in /Applications/XAMPP/xamppfiles/htdocs /storage/vendor/google/cloud-core/src/RequestWrapper.php:263 堆栈跟踪:#0 /Applications/XAMPP/xamppfiles/htdocs/storage/vendor/google/cloud-core/src/RequestWrapper.php(168) : Google\Cloud\Core\RequestWrapper->convertToGoogleException(Object(GuzzleHttp\Exception\ClientException))
1 /Applications/XAMPP/xamppfiles/htdocs/storage/vendor/google/cloud-core/src/Upload/MultipartUploader.php(65):
Google\Cloud\Core\RequestWrapper->send(Object(GuzzleHttp\Psr7\Request), Array) #2 /Applications/XAMPP/xamppfiles/htdocs/storage/vendor/google/cloud-storage/src/Bucket.php(283 ): Google\Cloud\Core\Upload\MultipartUploader->upload() #3 /Applications/XAMPP/xamppf 在 /Applications/XAMPP/xamppfiles/htdocs/storage/vendor/google/cloud-core/src/RequestWrapper.php 上第 263 行
请帮帮我!
提前致谢!
解决方案
密钥文件配置必须提供给被调用的客户端。ServiceBuilder 通常很方便,因为它允许您使用配置创建单个实例,并将该配置传递给每个新客户端。
在您的示例中,您创建了一个带有密钥文件的 ServiceBuilder 实例,但您没有使用该实例来调用 Storage。
两种选择:
use Google\Cloud\Core\ServiceBuilder;
$cloud = new ServiceBuilder([
'keyFilePath' => 'my-keyfile.json'
]);
$storage = $cloud->storage();
或者
use Google\Cloud\Storage\StorageClient;
$storage = new StorageClient([
'keyFilePath' => 'my-keyfile.json'
]);
在这两个示例中,$storage
都应该经过身份验证并可以使用!
推荐阅读
- azure - 阻止与微服务相关的 AKS 公共 URL 并保留它们以供内部通信
- api - Icinga2 事件插件命令通过 api 启动 rundeck 作业
- python - Azure:使用 Python 脚本在 virtual_network 类中检索“address_space”
- sql - 在 Oracle Sql Developer 中计算和存储派生属性
- latex - 如何在第一行下方创建带有子标题的多行多列表
- multithreading - 具有性能记录的多线程基于频率的采样
- ros - ROS 主题尚未发布
- typescript - 带有 typescript 的示例 React Native 项目有很多类型错误
- pine-script - 试图找到自高点以来的酒吧
- node.js - Redis 变慢了