HOWTO create GoogleCredential by using Service Account JSON
I was able to solve this by digging in to the source code for GoogleCredential
itself on github (which as of now resides here).
Turns out the version of google-api-java-client
that was existing in my code was slightly dated. I upgraded it to the latest one 1.20.0
& I am able to now directly specify the JSON object created to create the GoogleCredential. I wish Google would have updated their documentation.
Here is the code snippet,
InputStream resourceAsStream = AuthTest.class.getClassLoader().getResourceAsStream("Google-Play-Android-Developer.json");
GoogleCredential credential = GoogleCredential.fromStream(resourceAsStream);
That simple.
Chantz
Updated on September 11, 2020Comments
-
Chantz almost 4 years
I am using the Java SDK for
Android Publisher v2
andOauth2 v2
. Once I created the service account I was provided with a JSON ofGoogle Play Android Developer
service account with client id, email, private key etc. I have tried to look around and figure out how to create a Credential so that I use the AndoirdPublisher service to fetch info on my Android App's users subscriptions, entitlements etc and store this info on our backend servers.I am getting hard time trying to figure out how to go about this. None of the documentations I have seen so far help in creating
GoogleCredential
using the downloaded JSON.For example there is this documentation but it mentions only about P12 file and not the JSON. I want to avoid P12 if possible since I have multiple clients & I would like to save this JSON in some sort of database & then use it to create credential for each client.
Just to clarify I am trying to create the GoogleCredential object as described here,
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 com.google.api.services.sqladmin.SQLAdminScopes; // ... String emailAddress = "[email protected]"; JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); GoogleCredential credential = new GoogleCredential.Builder() .setTransport(httpTransport) .setJsonFactory(JSON_FACTORY) .setServiceAccountId(emailAddress) .setServiceAccountPrivateKeyFromP12File(new File("MyProject.p12")) .setServiceAccountScopes(Collections.singleton(SQLAdminScopes.SQLSERVICE_ADMIN)) .build();
But instead of setting the Service Account using P12 File like so
setServiceAccountPrivateKeyFromP12File()
, I want to use the JSON that carries the same info & generated when I created the service account.