我正试图通过手动传递服务帐户密钥作为Json对象与谷歌存储进行身份验证。我试图通过一个特定的服务帐户被使用,而不是由项目创建的默认服务帐户。然而,即使我传递了特定服务帐户的密钥,我得到的错误仍然是使用默认服务帐户。我如何告诉谷歌存储api使用传递给它的密钥?
var accessKey = {
"type": "service_account",
"project_id": "...",
"private_key_id": "...",
"private_key": "...",
"client_email": "myserviceaccount@gcp-serviceaccounts-keys.iam.gserviceaccount.com",
"client_id": "...",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "..."
};
const projectId = " ...";
const { Storage } = require('@google-cloud/storage');
const storage = new Storage({projectId, accessKey});
const bucket = storage.bucket('test-bucket-aa');
我得到的错误:
Error: gcp-myprojectid@appspot.gserviceaccount.com does not have storage.objects.get access to the Google Cloud Storage object.
最好将密钥保存在源代码之外。
存储客户端需要一个密钥文件名的引用。
参见:存储示例
将源代码中的字符串放入文件中,例如key.json
,然后:
const keyFilename = "/path/to/key.json";
const storage = new Storage({
projectId: projectId,
keyFilename: keyFilename
});
使用具有云功能和云存储的adc
PROJECT=... # Your Project ID
ACCOUNT=... # Your Service Account
FUNCTION=... # Your Cloud Function
# Create Service Account
gcloud iam service-accounts create ${ACCOUNT}
--description="Used by Cloud Functions to Access Cloud Storage"
--display-name="Cloud Functions Storage Accessor"
--project=${PROJECT}
EMAIL="${ACCOUNT}@${PROJECT}.iam.gserviceaccount.com"
ROLE="roles/storage.objectAdmin"
# Permit the Service Account `storageAdmin`
gcloud projects add-iam-policy-binding ${PROJECT}
--member=serviceAccount:${EMAIL}
--role=roles/${ROLE}
# Deploy the Cloud Functions to run as the Service Account
# Cloud Functions uses ADCs to auth as the Service Account
gcloud functions deploy ${FUNCTION}
...
--service-account=${EMAIL}
--project=${PROJECT}
注意使用上述方法,您的代码使用
const storage = new Storage();
更简单,平台验证使用服务帐户凭据。
注意最好是在一个特定的桶上设置IAM策略,而不是在项目(它的所有桶)上,参见:https://cloud.google.com/storage/docs/access-control/iam#project-level_roles_vs_bucket-level_roles
也许,代替gcloud projects add-iam-policy-binding
,你可以:
BUCKET=gs://[[YOUR-BUCKET]]
gsutil iam ch serviceAccount:${EMAIL}:roles/${ROLE} ${BUCKET}
https://cloud.google.com/storage/docs/gsutil/commands/iam ch