Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invalid_grant error with Google Cloud Storage and Service Account

I'm getting an invalid_grant error when I try to access Google Cloud Storage API with Service Accounts. I can't figure out what's wrong with the following code. Any idea ? It's my first application using Google Storage API. Any help will be greatly appreciated.

Source Code

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());
        }
    }
}

Error and stack trace

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)
like image 989
Jerome Serrano Avatar asked Aug 28 '13 21:08

Jerome Serrano


1 Answers

This error was due to an incorrect Service Account ID. I was using the Client ID (ending in .apps.googleusercontent.com) instead of the email address (ending in @developer.gserviceaccount.com). There is no problem with the email address.

like image 132
Jerome Serrano Avatar answered Nov 01 '22 17:11

Jerome Serrano