How to set GOOGLE_APPLICATION_CREDENTIALS in spring boot app
Asked Answered
A

8

12

I am attempting to use the google vision library in java. The steps specify that I need to setup my auth credentials in order to start using the this library . I was able to generate my json property file from API Console Credentials page and I placed it in my spring boot app in the resources folder.

I think updated my application.properties file to include the value like so:

GOOGLE_APPLICATION_CREDENTIALS=datg-avatar-generator-9dc9155cd5bd.json

I'm also setting my property source in my controller like so:

@PropertySource("${GOOGLE_APPLICATION_CREDENTIALS}")

However, after doing that I'm still getting an error saying:

java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
Archenemy answered 24/10, 2017 at 23:28 Comment(3)
A JSON file isn't a properties file. You seem to be mixing up various configuration systems. Show more code, specifically how you're instantiating whatever's throwing that exception, and we may be able to guide you on how to inject the value.Stoical
ok, thanks for the comment. I think the google doc on how to use these properties says to set the environment variable to point to the json file though: developers.google.com/identity/protocols/…Archenemy
Okay, that's different from setting something in application.properties. Spring Boot has a really useful system that lets you compile configuration properties from several sources (files, command line, environment variables), but a non-Spring component that says it needs an environment variable needs a real environment variable (unless there's a constructor that takes the file argument, which it should have, but not all library authors are so wise).Stoical
T
15

I was able to configure this property using Spring Cloud GCP spring-cloud-gcp-starter-data-datastore, creating a service account project owner, copy the JSON private key to the main resources directory, and setting the following properties in the application.properties

spring.cloud.gcp.project-id=<project-id>
spring.cloud.gcp.credentials.location=classpath:<credentials-private-key>.json

from the documentation

You can find the project id by visiting this page https://support.google.com/googleapi/answer/7014113?hl=en Go to the API Console.

From the projects list, select Manage all projects. The names and IDs for all the projects you're a member of are displayed. You can also select the project go the settings and see the project ID

Teleran answered 29/5, 2020 at 11:33 Comment(1)
Oh, my. I spent a couple of days pulling my hair out because this didn't work at my project. Then, I realized I was using the wrong property. I'm also using BigQuery and I had "spring.cloud.gcp.bigquery.credentials.location" which worked, but gcp-starter-storage didn't. There are general properties which can be used for all google cloud projects. Those are "spring.cloud.gcp.project-id" and "spring.cloud.gcp.credentials.location".Provide
H
2

You need to set the shell variable. Run this command before mvn run.

export GOOGLE_APPLICATION_CREDENTIALS="/Users/ronnyshibley/Dev/eddress-service-key.json"
Houseline answered 4/8, 2018 at 11:25 Comment(2)
Is there a way to do it from the application? Either by Spring or Java functions?Crosse
try envFile plugin of you are using intellijJarv
S
2

You can use application properties, but you need to use a different StorageOptions builder.

You are probably using

private static Storage storage = StorageOptions.getDefaultInstance().getService(); 

But if you want to skip the environment variable you need to use:

Credentials credentials = GoogleCredentials
  .fromStream(new FileInputStream("path/to/file"));
Storage storage = StorageOptions.newBuilder().setCredentials(credentials)
  .setProjectId("my-project-id").build().getService();

Note that the default builder (using environment variables) is better if you are going to deploy your applications to cloud, because then this is automatically filled for you.

Sickle answered 22/4, 2021 at 7:40 Comment(0)
I
1

For authentication using the service account key, you can set the Environment Variable in your shell.

export GOOGLE_APPLICATION_CREDENTIALS="/Users/username/directory/service-key-file-name.json"

Then you need to start your IDE from the same session. I was stuck after exporting and setting up the environment variable and was still unable to use it.

I tried quitting the current IDE window and restarted the IDE again from the same session. In my case it was Intellij, so in the terminal itself,

cd project directory
idea .

Or you can also add the environment variable in your bash profile and then source it.

Immortal answered 26/5, 2021 at 7:44 Comment(0)
U
1

I have tried several ways to do this, and none of them worked. Maven plugin environmentVariables is the last thing that worked without any problem.

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <fork>true</fork>
                <executable>true</executable>
                <environmentVariables>
                    <GOOGLE_APPLICATION_CREDENTIALS>/path/to/the/service-account.json</GOOGLE_APPLICATION_CREDENTIALS>
                </environmentVariables>
            </configuration>
        </plugin>
    </plugins>
</build>
Unicycle answered 6/1, 2023 at 22:36 Comment(0)
M
1

You need to add env variable

GOOGLE_APPLICATION_CREDENTIALS=<path to google project json file >

If you are using IntelliJ idea, Edit the Project configuration and add the Environment variable

For images check this

https://www.twilio.com/blog/set-up-env-variables-intellij-idea-java

Murmur answered 11/2, 2023 at 4:12 Comment(0)
S
0

You can load your JSON key file like this:

// Load the JSON key and create a TranslationServiceClient:
public TranslationServiceClient getTranslationClient() throws IOException {
    InputStream credentialsStream = getClass().getResourceAsStream("/key.json");
    Credentials credentials = GoogleCredentials.fromStream(credentialsStream);

    TranslationServiceSettings settings = TranslationServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
            .build();

    return TranslationServiceClient.create(settings);
}

And this is the usage:

// Replace [YOUR_PROJECT_ID] with your Google Cloud Project ID
public void translateText() {
    try (TranslationServiceClient client = getTranslationClient()) {
        LocationName parent = LocationName.of("[YOUR_PROJECT_ID]", "global");

        TranslateTextRequest request = TranslateTextRequest.newBuilder()
                .setParent(parent.toString())
                .setMimeType("text/plain")
                .setSourceLanguageCode("en-US")
                .setTargetLanguageCode("es")
                .addContents("Hello, World!")
                .build();

        TranslateTextResponse response = client.translateText(request);
        String translatedText = response.getTranslationsList().get(0).getTranslatedText();
        System.out.println(translatedText);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Remember to be cautious with the key.json file. Ensure it isn't publicly accessible, as misuse can result in unexpected charges on your Google Cloud account.

Scriptwriter answered 7/9, 2023 at 20:23 Comment(0)
H
0

If you are using windows then use

set GOOGLE_APPLICATION_CREDENTIALS="D:\Cloud\service\googleCloudKey.json"

Harlem answered 27/4, 2024 at 13:28 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.