Search code examples
javasshgoogle-apissh-tunnelgoogle-directory-api

Using Google Direcory API with SSH Tunnel


Error:

com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request { "error" : "invalid_scope", "error_description" : "https://www.googleapis.com:22230/auth/admin.directory.user is not valid scope." }

We have a java application deployed in WAS which will use Google Directory API. WAS is placed in the application layer and is not allowed to access Google API on internet. Hence the network team opened an SSH tunnel so that WAS can access Google API over a different port(22230) than the default ssl port of 443. Updated the java code to use the scope value with the new port, but ended up with the "invalid_scope" error mentioned above.

SCOPES = Arrays.asList(""https://www.googleapis.com:22230/auth/admin.directory.user"); credential = new GoogleCredential.Builder() .setTransport(httpTransport) .setJsonFactory(jsonFactory) .setServiceAccountUser(properties.getProperty(ACCT_USER)) .setServiceAccountId(properties.getProperty(ACCT_ID)) .setServiceAccountScopes(SCOPES) .setServiceAccountPrivateKeyFromP12File( p12 ) .build();

Googling did not help me to find much on SSH tunnel & Google API usage. Any help would be greatly appreciated. Is there a recommended way to use Google Directory API, when SSH tunneling is done?


Solution

  • You will need to overwrite the "tokenServerEncodedUrl" parameter value in the GoogleCredential object, and "rootUrl" parameter value in the Directory object for using your non-standard SSH Tunnel Ports for GoogleAPI client communication.

    Use the following code snippet to achieve it:

    GoogleCredential credential = (new com.google.api.client.googleapis.auth.oauth2.GoogleCredential.Builder()).setTransport(httpTransport).setJsonFactory(jsonFactory).setTokenServerUrl(new GenericUrl("https://accounts.google.com:ssh-port/o/oauth2/token")).setServiceAccountUser(ACCT_USER).setServiceAccountId(ACCT_ID).setServiceAccountScopes(SCOPES).setServiceAccountPrivateKeyFromP12File(p12).build();

    Directory service = (new com.google.api.services.admin.directory.Directory.Builder(httpTransport, jsonFactory, null)).setHttpRequestInitializer(credential).setRootUrl("https://www.googleapis.com:22230/").setApplicationName(APP_NAME).build();

    The above code snippet shall overwrite the default service URL values set by the Google API Client libraries (Jar files).