Use a .p12 File from classpath for GoogleCredential

匆匆过客 提交于 2019-12-01 19:31:23
CobraEnergyDrink

After digging through the GoogleCredential.Builder class source code I realized the following:

  • the password for the p12 file generated from Google's developer console is always "notasecret" as well as the password for the alias
  • the alias for the private key is always "privatekey"

using the following code to build the private key from the resource InputStream:

KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(this.getClass().getClassLoader().getResourceAsStream("Credentials.p12"), "notasecret".toCharArray());
PrivateKey pk = (PrivateKey)keystore.getKey("privatekey", "notasecret".toCharArray());

I was able to load the private key into the GoogleCredential Builder:

GoogleCredential credential = new GoogleCredential.Builder()
                    .setTransport(httpTransport)
                    .setJsonFactory(jsonFactory)
                    .setServiceAccountId("xxxxxx@developer.gserviceaccount.com")
                    .setServiceAccountScopes(Arrays.asList(DirectoryScopes.ADMIN_DIRECTORY_GROUP, DirectoryScopes.ADMIN_DIRECTORY_USER, DirectoryScopes.ADMIN_DIRECTORY_ORGUNIT))
                    .setServiceAccountUser(emailAccount)
                    .setServiceAccountPrivateKey(pk) //<----THIS
                    .build();

Or you can just specify the key file when instantiating the the credential.

GoogleCredential credential = new GoogleCredential.Builder()
            .setTransport(httpTransport)
            .setJsonFactory(JSON_FACTORY)
            .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
            .setServiceAccountPrivateKeyFromP12File(new File(KEY_FILE_LOCATION))
            .setServiceAccountScopes(AnalyticsScopes.all())
            .build();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!