如何管理对 Google Cloud Storage (Node.js) 中对象的权限?

问题描述

我正在使用谷歌云存储 node.js 客户端 sdk,我想设置对从 Node.js 上传的对象的权限。

例如,我只希望经过身份验证的用户(我自己管理身份验证/授权)能够访问某些文件,而其他文件是公开可用的,但不知道如何实现。

这就是我想要的

const myBucket = storage.bucket('files_bucket')
const fileRef = myBucket.file('some_file.pdf')

// Here I authenticate the user
const [isAuthenticated,user] = await authenticate(username,password)

if (!isAuthenticated) {
  // The only method I found of making file public,doesnt seem to work
  await fileRef.makePublic()
} else {
  const userRole = user.role // either 'admin' or 'client'

  // How can I make this file private to all users with certain role
  await fileRef.makePrivate()
}

顺便说一句,makePublic 似乎没有公开文件,因为一旦我尝试访问它的 URL,我就会得到

{
  "error": {
    "code": 401,"message": "Anonymous caller does not have storage.objects.getIamPolicy access to the Google Cloud Storage object.","errors": [
      {
        "message": "Anonymous caller does not have storage.objects.getIamPolicy access to the Google Cloud Storage object.","domain": "global","reason": "required","locationType": "header","location": "Authorization"
      }
    ]
  }
}

解决方法

如评论中所述,您未使用 Cloud Storage 身份验证或 Google OAuth2 服务,因此您的用户在 Cloud Storage 中显示为 Anonymous caller,不允许访问您的资源,服务被拒绝。

可以在不使用 Google 直接身份验证的情况下为您的用户执行此操作,因此您可以自行管理身份验证/授权,但在尝试访问 GCS 资源(或其他 GCP 产品)时,您将需要模拟一个服务帐户显示为 GCS 的经过身份验证的调用者,此时特定文件的自动化背后的逻辑将取决于您的代码。

为了通过 GCS 库的服务帐户设置访问权限,您可以使用 these instructions in the documentation