将特定服务帐户密钥传递给 Google 存储 API

Pass specific service account key to Google Storage API

我正在尝试通过将服务帐户密钥作为 Json 对象手动传递给 Google 存储进行身份验证。我正在尝试传递要使用的特定服务帐户,而不是项目创建的默认服务帐户。但是,即使我传递了特定服务帐户的密钥,我得到的错误仍在使用默认服务帐户。我如何告诉 google 存储 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. 

最好不要将密钥放在源代码中。

存储客户端需要对密钥文件名的引用。

参见:Storage examples

将源代码中的字符串放入文件中,例如key.json 然后:

const keyFilename = "/path/to/key.json";
const storage = new Storage({
  projectId: projectId,
  keyFilename: keyFilename
});

将 ADC 与 Cloud Functions 和 Cloud Storage 结合使用

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}

NOTE Using the above approach, your code is simpler using just const storage = new Storage();, the platform auth's using the Service Accounts credentials.

NOTE It's preferable to set the IAM policy on a specific bucket rather than the project (all its buckets), see: 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