Authenticating Google DLP API from Java without setting GOOGLE_APPLICATION_CREDENTIALS?

I'm playing around with the Google Cloud DLP Java library. I've set up my service credentials and saved them in a JSON file per the instructions here: The documentation states that the preferred way to authenticate is by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS to point to the path of the JSON file that contains the credentials. This is not all that practical in my case. I have a Spring Boot application where all the code (as well as the JSON file with the credentials) is embedded in a "fat jar". I can easily use the class loader to obtain an InputStream to the resource, but I can't really point to it inside the jar file from an environment variable. It's also not practical to create an environment variable from within a running JVM without resorting to hacks like using reflection, etc.

Some other Google Cloud libraries have service classes that can be initialized with a GoogleCredentials object, but I haven't found a way of doing this with the DLP library. Is there any way of passing a GoogleCredentials into the DlpServiceClient?

1 answer

  • answered 2018-02-13 01:30 user2337270

    I ended up figuring it out after quite a bit of Googling. This worked fine:

    Resource r = new ClassPathResource("/path-to-my-cred-file.json");
    GoogleCredentials creds = GoogleCredentials.fromStream(r.getInputStream());    
    DlpServiceSettings settings = DlpServiceSettings.newBuilder()
    try (DlpServiceClient dlpServiceClient = DlpServiceClient.create(settings)) {
    ... other stuff here ...