I am doing in google api service using google service account. I have this problem how to set value for builder to credential this api. How to set it in JSON key
public GoogleCredential googleCredential() throws GeneralSecurityException, IOException {
Collection<String> scope = new ArrayList<String>();
scope.add("https://www.googleapis.com/auth/drive");
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
Builder credentialBuilder = new Builder(httpTransport, jsonFactory);
return new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId("xxx")
.setServiceAccountScopes(scope)
)
.build();
}
I want to create application.yml to store this JSON key like this:
google-drive:
type: "service_account",
project_id: "xx-387809",
private_key_id: "xxxxxxx",
private_key: "-----BEGIN PRIVATE KEY-----xxxxxxx-----END PRIVATE KEY-----\n",
client_email: "xxxxx-387809.iam.gserviceaccount.com",
client_id: "00000000",
auth_uri: "https://accounts.google.com/o/oauth2/auth",
token_uri: "https://oauth2.googleapis.com/token",
auth_provider_x509_cert_url: "https://www.googleapis.com/oauth2/v1/certs",
client_x509_cert_url: "https://www.googleapis.com/robot/v1/metadata/x509/xxxxxxx-387809.iam.gserviceaccount.com",
universe_domain: "googleapis.com"
to run my service with this config
You can pass the JSON key as a String application property for example on the application.yml
google:
privateKey:
json: '{"type":"service_account","project_id":"mocked-project","private_key_id":"mocked_private_key","private_key":"-----BEGIN PRIVATE KEY-----xxxxxxx-----END PRIVATE KEY-----\n","client_email":"mocked-service-account@mocked-project.iam.gserviceaccount.com","client_id":"123577123897123","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_x509_cert_url":"https://www.googleapis.com/robot/v1/metadata/x509/mock-service-account%40mocked-project.iam.gserviceaccount.com"}'
Then you can parse the credentials with the fromStream()
method GoogleCredentials
, for example:
InputStream in = new ByteArrayInputStream(privateKeyJson.getBytes());
GoogleCredential cr = GoogleCredential.fromStream(in);
Finally, after obtaining the credentials you can use the GoogleCredentials.Builder()
to set the service account properties
Here is an example:
GoogleCredential cr = GoogleCredential.fromStream(in);
return new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jacksonFactory)
.setServiceAccountId(cr.getServiceAccountId())
.setServiceAccountPrivateKey(cr.getServiceAccountPrivateKey())
.setServiceAccountPrivateKeyId(cr.getServiceAccountPrivateKeyId())
.setTokenServerEncodedUrl(cr.getTokenServerEncodedUrl())
.setServiceAccountId("xxx")
.setServiceAccountScopes(scope)
.build();