當我嘗試使用服務帳戶訪問Google Cloud Storage API時,出現invalid_grant錯誤。我無法弄清楚下面的代碼有什麼問題。任何想法 ?這是我使用Google Storage API的第一個應用程序。任何幫助將不勝感激。Google雲端存儲和服務帳戶出現invalid_grant錯誤
源代碼
public static void main(String[] args) throws Exception {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
List<String> scopes = new ArrayList<String>();
scopes.add(StorageScopes.DEVSTORAGE_FULL_CONTROL);
Credential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId("XXXX")
.setServiceAccountPrivateKeyFromP12File(new File("key.p12"))
.setServiceAccountScopes(scopes).build();
Storage storage = new Storage.Builder(httpTransport, jsonFactory,
credential).setApplicationName("test")
.build();
List<String> list = new ArrayList<String>();
List<Bucket> buckets = storage.buckets().list("XXXX").execute().getItems();
if(buckets != null) {
for(Bucket b : buckets) {
list.add(b.getName());
}
}
}
錯誤和堆棧跟蹤
Exception in thread "main" com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
"error" : "invalid_grant"
}
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:269)
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:858)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:410)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460)
at GoogleStorageFetcher.main(GoogleStorageFetcher.java:143)
槽糕......我看不出有什麼錯。您的服務帳戶看起來像一個很長的電子郵件地址,以「@ developer.gserviceaccount.com」結尾,對吧?和「key.p12」是在這樣打開的正確的地方?可能值得嘗試命令行示例應用程序以確保您的憑據有效:https://code.google.com/p/google-api-java-client/source/browse/plus-serviceaccount-cmdline-sample/? repo = samples&r = 1dd135aa1dfa0b5d326ba2a0c795ed18cd052495 –
謝謝。實際上,我使用的是客戶端ID(以.apps.googleusercontent.com結尾)而不是電子郵件地址(以@ developer.gserviceaccount.com結尾)。 –