简体   繁体   中英

How to manage permissions to an object in Google Cloud Storage (Node.js)?

I'm using the google cloud storage node.js client sdk, and I want to set permissions to an uploaded object from Node.js.

For instance, I want only authenticated users (I manage authentication/authorization myself) to be able to access certain files, and other files to be publicly available, But can't understand how to achieve that.

This is what I want to achieve

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()
}

Btw, makePublic doesnt seem to make the file public, because once i try to access its URL, i get

{
  "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"
      }
    ]
  }
}

As mentioned in the comments you are not using Cloud Storage Authentication nor Google OAuth2 service, and therefore your user appears as an Anonymous caller to Cloud Storage, which is not allowed to access your resources and service is denied.

It is possible to do this without using direct authentication with Google for your users, therefore managing authentication/authorization by yourself, but when trying to access GCS resources (or other GCP products for that matter) you are going to need to inpersonate a service account to appear as an authenticated caller for GCS, the logic behind autorization to particular files will be up to your code at this point.

In order to setup access through a service account for the GCS library you can use these instructions in the documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM