Google云端存储和服务帐户存在invalid_grant错误

时间:2013-08-28 21:51:55

标签: java oauth-2.0 google-cloud-storage

当我尝试使用服务帐户访问Google云端存储API时,我收到了invalid_grant错误。我无法弄清楚以下代码有什么问题。任何的想法 ?这是我使用Google Storage API的第一个应用程序。任何帮助将不胜感激。

源代码

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)

2 个答案:

答案 0 :(得分:22)

此错误是由于服务帐户ID不正确造成的。我使用的是客户端ID(以.apps.googleusercontent.com结尾)而不是电子邮件地址(以@ developer.gserviceaccount.com结尾)。电子邮件地址没有问题。

答案 1 :(得分:9)

我知道这个问题是从一年前开始的。

我遇到了这个错误:错误:“invalid_grant”,说明:“”,Uri:“”

就我而言,解决了服务器时钟与NTP同步的问题。我服务器的防火墙阻塞了一个端口,服务器的时间没有正确更新。

有关详细信息,请visit this Google page.