我正在尝试使用服务帐户获取我的Google云计算项目中的Buckets列表。
以下是该计划:
package com.mypackage.api;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.api.services.storage.Storage;
import com.google.api.services.storage.StorageScopes;
import com.google.api.services.storage.model.Bucket;
public class TestClass {
public static void main(String args[]) throws IOException, GeneralSecurityException {
String project = "my-project";
Storage storage = createStorageService();
List<String> list = new ArrayList<String>();
List<Bucket> buckets = storage.buckets().list(project).execute().getItems();
if(buckets != null) {
for(Bucket b : buckets) {
list.add(b.getName());
}
}
}
public static Storage createStorageService() throws IOException, GeneralSecurityException {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
GoogleCredential credential = GoogleCredential.getApplicationDefault();
if (credential.createScopedRequired()) {
credential = credential.createScoped(Arrays.asList(StorageScopes.DEVSTORAGE_FULL_CONTROL, "https://www.googleapis.com/auth/cloud-platform"));
}
return new Storage.Builder(httpTransport, jsonFactory,
credential).setApplicationName("My Application")
.build();
}
}
我收到以下错误:
Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "mytool@my-project.iam.gserviceaccount.com does not have storage.buckets.list access to project 333XXXXX67.",
"reason" : "forbidden"
} ],
"message" : "mytool@my-project.iam.gserviceaccount.com does not have storage.buckets.list access to project 333XXXXX67."
}
我已将“所有者”范围添加到我的服务帐户中。但我仍然得到许可被拒绝错误。
感谢任何帮助。
答案 0 :(得分:0)
检查您的凭证。您确定credential.createScopedRequired()是否为true,并且credentional获取读取信息所需的范围?例如https://www.googleapis.com/auth/devstorage.read_only。这样的答案(403)意味着您没有许可。
答案 1 :(得分:0)
我通过更改凭据类型文件来纠正此错误。最初,我拿了web应用程序文件,这就是我收到此错误的原因。感谢您回答我的问题。