繁体   English   中英

找不到 GOOGLE_APPLICATION_CREDENTIALS

[英]GOOGLE_APPLICATION_CREDENTIALS can't be found

目前必须将 Google Cloud Platform 服务集成到我的应用中,但收到以下异常:

**W/System.err: 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.
        at com.google.auth.oauth2.DefaultCredentialsProvider.getDefaultCredentials(DefaultCredentialsProvider.java:134)
W/System.err:     at com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:119)
        at com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:91)
        at com.google.api.gax.core.GoogleCredentialsProvider.getCredentials(GoogleCredentialsProvider.java:67)
        at com.google.api.gax.rpc.ClientContext.create(ClientContext.java:135)
        at com.google.cloud.speech.v1.stub.GrpcSpeechStub.create(GrpcSpeechStub.java:94)
        at com.google.cloud.speech.v1.stub.SpeechStubSettings.createStub(SpeechStubSettings.java:131)
        at com.google.cloud.speech.v1.SpeechClient.<init>(SpeechClient.java:144)
        at com.google.cloud.speech.v1.SpeechClient.create(SpeechClient.java:126)
        at com.google.cloud.speech.v1.SpeechClient.create(SpeechClient.java:118)
        at com.dno.app.ui.TranscriptFragment$1.onClick(TranscriptFragment.java:72)**

设置环境变量:

环境变量

.json 文件在这里:

.json 文件

应用程序在此代码块(片段)中的 authImplicit() 处崩溃:

    transcriptBtn = getActivity().findViewById(R.id.transcript_button);
    transcriptBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try (SpeechClient speechClient = SpeechClient.create()) {
                authImplicit(); // issue with Google Platform Login Authentification
                // - does not read the environment variable, and therefore cannot get access to the .json file.

                // The path to the audio file to transcribe
                String fileName = getFile().getName();

                // Reads the audio file into memory
                Path path = Paths.get(fileName);

                byte[] data = Files.readAllBytes(path);
                ByteString audioBytes = ByteString.copyFrom(data);

                // Builds the sync recognize request
                RecognitionConfig config =
                        RecognitionConfig.newBuilder()
                                .setEncoding(RecognitionConfig.AudioEncoding.FLAC)
                                .setSampleRateHertz(16000)
                                .setLanguageCode("en-US")
                                .build();
                RecognitionAudio audio = RecognitionAudio.newBuilder().setContent(audioBytes).build();

                // Performs speech recognition on the audio file
                RecognizeResponse response = speechClient.recognize(config, audio);
                List<SpeechRecognitionResult> results = response.getResultsList();

                for (SpeechRecognitionResult result : results) {
                    // There can be several alternative transcripts for a given chunk of speech. Just use the
                    // first (most likely) one here.
                    SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
                    System.out.printf("Transcription: %s%n", alternative.getTranscript());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

authImplicit() 的代码:

 private void authImplicit() {
        // If you don't specify credentials when constructing the client, the client library will
        // look for credentials via the environment variable GOOGLE_APPLICATION_CREDENTIALS.
        Storage storage = StorageOptions.getDefaultInstance().getService();

        System.out.println("Buckets:");
        Page<Bucket> buckets = storage.list();
        for (Bucket bucket : buckets.iterateAll()) {
            System.out.println(bucket.toString());
        }
    }

我选择了所有者类型的服务帐户,因此我不应该缺少任何权限。

编辑(仍然无法正常工作):我尝试使用此示例,但仍然无法正常工作: 应用程序默认凭据不可用

编辑#2 (在服务器端工作):事实证明,谷歌目前不支持 Android 执行此任务。 此后,我将代码移至 ASP.NET 后端,现在代码运行顺畅。

感谢您提供以下帮助。

我可以理解您已阅读文档并实施了此处所述的所有步骤 - https://cloud.google.com/storage/docs/reference/libraries#windows

  1. 正如@John Hanley 提到的,您是否检查了打印环境变量?

  2. 它绝对不是与所有者相关的权限问题,因为异常说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. 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.

现在,要解决这个问题,您是否只想使用环境变量? 还是其他方法都可以?

如果您对其他方法没问题,请查看此代码

private void authImplicit() {

    //please give exact file name for this credentials.json
    Credentials credentials = GoogleCredentials
      .fromStream(new FileInputStream("C:\\Users\\dbgno\\Keys\\credentials.json"));
    Storage storage = StorageOptions.newBuilder().setCredentials(credentials)
      .setProjectId("Some Project").build().getService();

    System.out.println("Buckets:");
    Page<Bucket> buckets = storage.list();
    for (Bucket bucket : buckets.iterateAll()) {
        System.out.println(bucket.toString());
    }
}

编辑 1:致力于解决方案试试这个,看看您是否可以阅读您作为输入提供的 JSON 文件。 打印语句应显示您打算使用的服务帐户进行身份验证

    public static Credential getDriveService(String fileLocation, String servAccAdmin)
      throws IOException {
    HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();

    GoogleCredential googleCredential =
        GoogleCredential.fromStream(new FileInputStream(fileLocation), httpTransport, jsonFactory)
            .createScoped(SCOPES);
    System.out.println("--------------- " + googleCredential.getServiceAccountId());

    Credential credential = new GoogleCredential.Builder()
        .setTransport(googleCredential.getTransport())
        .setJsonFactory(googleCredential.getJsonFactory())
        .setServiceAccountPrivateKeyId(googleCredential.getServiceAccountPrivateKeyId())
        .setServiceAccountId(googleCredential.getServiceAccountId()).setServiceAccountScopes(SCOPES)
        .setServiceAccountPrivateKey(googleCredential.getServiceAccountPrivateKey())
        .setServiceAccountUser(servAccAdmin).build();

    return credential;
}

编辑2:

当我们看到一些凭证问题时,我正在尝试查看我访问任何其他谷歌 API 服务的方式,可能是驱动器或 gmail,我们手动传递密钥文件并构建凭证,这些凭证应该用于进一步的服务调用. 现在尝试添加这些依赖项,这只是通过使用我们访问 google drive/gmail 等的相同方式进行故障排除。我们将了解 google cloud api 是否能够构建凭证

<dependency>
  <groupId>com.google.http-client</groupId>
  <artifactId>google-http-client</artifactId>
  <version>${project.http.version}</version>
</dependency>
<dependency>
  <groupId>com.google.http-client</groupId>
  <artifactId>google-http-client-jackson2</artifactId>
  <version>${project.http.version}</version>
</dependency>
<dependency>
  <groupId>com.google.oauth-client</groupId>
  <artifactId>google-oauth-client-jetty</artifactId>
  <version>${project.oauth.version}</version>
</dependency>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM