【问题标题】:Create bucket for public access with service account使用服务帐户创建用于公共访问的存储桶
【发布时间】:2021-01-06 09:36:12
【问题描述】:

我正在以编程方式创建一个存储桶,如下所示:

String bucketName = UUID.randomUUID().toString();

List<Acl> aclList = new ArrayList<>();
if (gcsBucketEntity.isPublic()) {
    Acl publicAccessAcl = Acl.newBuilder(Acl.User.ofAllUsers(), Acl.Role.READER).build();
    aclList.add(publicAccessAcl);
}

BucketInfo bucketInfo = BucketInfo
        .newBuilder(bucketName)
        .setLocation(gcsBucketEntity.getLocation()) // Multi-regions
        .setStorageClass(valueOfStrict(gcsBucketEntity.getStorageType().toString()))
        .setAcl(aclList)
        .build();

Bucket bucket = this.storage.create(bucketInfo);   

我也尝试过设置BucketTargetOption

Storage.BucketTargetOption bucketTargetOption = Storage.BucketTargetOption
        .predefinedAcl(Storage.PredefinedAcl.PUBLIC_READ);

Bucket bucket = this.storage.create(bucketInfo, bucketTargetOption);

结果完全相同。

存储桶已创建,在 GCP 控制台中我可以看到访问权限是公开的。

但是,我无法访问任何文件,而是收到 AccessDenied 错误:

<Error>
  <Code>AccessDenied</Code>
  <Message>Access denied.</Message>
  <Details>Anonymous caller does not have storage.objects.get access to the Google Cloud Storage object.</Details>
</Error>

如果我手动创建 bucker,我想我必须为用户 allUsers 添加一个 Storage Object Viewer 角色:

这是我在手动和自动创建的存储桶之间看到的唯一区别,所以我的问题是..

如何以编程方式添加此权限?

【问题讨论】:

    标签: google-cloud-platform google-cloud-storage


    【解决方案1】:

    the docs中其实有一个例子。

    显然我们必须先创建存储桶,然后再设置 IAM 策略。

    BucketInfo bucketInfo = BucketInfo
            .newBuilder(bucketName)
            .setLocation(gcsBucketEntity.getLocation()) // Multi-regions
            .setStorageClass(valueOfStrict(gcsBucketEntity.getStorageType().toString()))
            .build();
    
    Bucket bucket = this.storage.create(bucketInfo);
    
    if (gcsBucketEntity.isPublic()) {
        Policy policy = this.storage.getIamPolicy(bucketName);
        this.storage.setIamPolicy(
                bucket.getName(),
                policy.toBuilder()
                        .addIdentity(StorageRoles.objectViewer(), Identity.allUsers())
                        .build()
        );
    }
    

    恕我直言,这有点奇怪,因为如果出现问题,我最终可能会得到一个“损坏”的存储桶。

    无论如何,上面的代码对我有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-15
      • 2019-11-16
      • 1970-01-01
      • 2019-06-13
      相关资源
      最近更新 更多