首页 > 解决方案 > 如何管理对 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"
      }
    ]
  }
}

标签: node.jsgoogle-cloud-platformgoogle-cloud-storage

解决方案


正如评论中提到的,您没有使用云存储身份验证或 Google OAuth2 服务,因此您的用户显示为Anonymous caller云存储,不允许访问您的资源并且服务被拒绝。

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

为了通过 GCS 库的服务帐户设置访问权限,您可以使用文档中的这些说明


推荐阅读