问题描述
我正在以编程方式创建一个存储桶,如下所示:
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,我想我必须向用户Storage Object Viewer
添加一个allUsers
角色:
这是我能看到的手动和自动创建的存储桶之间的唯一区别,所以我的问题是..
如何以编程方式添加此权限?
解决方法
实际上在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()
);
}
恕我直言,这有点奇怪,因为如果出现问题,我可能最终会得到一个“破”的桶。
无论如何,上面的代码对我有用。