Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use GAE Service Account JSON key

I have an application in GAE and I'm using a service account to call some google services. When I created a service account in the dashboard, a JSON key was provided to me. The content of the json is something like this:

{
  "private_key_id": "bar-foo",
  "private_key": "-----BEGIN PRIVATE KEY-----foo-bar\n-----END PRIVATE KEY-----\n",
  "client_email": "[email protected]",
  "client_id": "bar-foo.apps.googleusercontent.com",
  "type": "service_account"
}

How can I use this private_key in my java code to generate a GoogleCredential object?

I was able to do that using the setServiceAccountPrivateKeyFromP12File method but for that I would need to create a p12 file and have it stored somewhere. With the json private key I could have it configured in my properties file.

I found a setServiceAccountPrivate method in the GoogleCredential.Builder that receives a PrivateKey object as parameter but I don't know how to generate this object from the value inside the json. All examples that I found were using the p12 file.

like image 994
Luiz Guilherme Avatar asked Jul 16 '14 12:07

Luiz Guilherme


1 Answers

Since this question is still getting views and doesn't have an accepted answer, here is an example of how to use a JSON key with the Google API Client Library slightly adapted from the official documentation section 'Using OAuth 2.0 with the Google API Client Library for Java':

HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
...
// Build service account credential.

GoogleCredential credential = GoogleCredential.fromStream(MyClass.class.getResourceAsStream("/MyProject-1234.json"))
    .createScoped(Collections.singleton(PlusScopes.PLUS_ME));
  // Set up global Plus instance.
  plus = new Plus.Builder(httpTransport, jsonFactory, credential)
      .setApplicationName(APPLICATION_NAME).build();

You would place your keyfile eg. 'MyProject-1234.json' into /src/main/resources and 'MyClass' above refers to the name of the parent class containing your method.

like image 98
Adam Avatar answered Nov 01 '22 04:11

Adam