/** * Initializes OAuth2 credential from a private keyfile, as described in * <a href="https://developers.google.com/api-client-library/java/google-api-java-client/oauth2#service_accounts" * >Service accounts</a>. * * @param serviceAccountEmail Email address of the service account associated with the keyfile. * @param privateKeyFile Full local path to private keyfile. * @param scopes List of well-formed desired scopes to use with the credential. * @return a {@link com.google.auth.Credentials} object. * @throws java.io.IOException if any. * @throws java.security.GeneralSecurityException if any. */ public static Credentials getCredentialFromPrivateKeyServiceAccount( String serviceAccountEmail, String privateKeyFile, List<String> scopes) throws IOException, GeneralSecurityException { PrivateKey privateKey = SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(), new FileInputStream(privateKeyFile), "notasecret", "privatekey", "notasecret"); // Since the user specified scopes, we can't use JWT tokens return ServiceAccountCredentials.newBuilder() .setClientEmail(serviceAccountEmail) .setPrivateKey(privateKey) .setScopes(scopes) .setHttpTransportFactory(getHttpTransportFactory()) .build(); }
private GoogleCredentials getSourceCredentials() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountCredentials sourceCredentials = ServiceAccountCredentials.newBuilder() .setClientEmail(SA_CLIENT_EMAIL) .setPrivateKey(privateKey) .setPrivateKeyId(SA_PRIVATE_KEY_ID) .setScopes(SCOPES) .setProjectId(PROJECT_ID) .setHttpTransportFactory(transportFactory).build(); transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN); return sourceCredentials; }