【问题标题】:Google translate API V3: How to authenticate service account from file streamGoogle translate API V3:如何从文件流中验证服务帐户
【发布时间】:2021-09-26 20:49:09
【问题描述】:

使用 Google Translate V3 API 验证服务帐户的默认方式是通过环境变量。这个名为 GOOGLE_APPLICATION_CREDENTIALS 的 env var 指向一个带有凭证的 json 文件,如下所述: https://cloud.google.com/docs/authentication/production

但是,在其他位置使用文件时,如何使用所需的凭据?我可以从 FileStream 创建凭据对象,如 google 文档中所述。但是,使用此凭证对象仅适用于谷歌云存储。 TranslateTextRequest 的构建器不接受这样的凭证对象。 https://googleapis.dev/dotnet/Google.Cloud.Translate.V3/2.0.0/api/Google.Cloud.Translate.V3.TranslateTextRequest.html

唯一的解决方法是将文件复制到环境变量中指定的位置,但这看起来很奇怪,并且在未设置该变量时会失败。

【问题讨论】:

  • 您使用哪种语言/SDK?从文档。链接似乎是.NET,但我不确定。
  • 使用 TranslationServiceClientBuilder 并指定 JsonCredentials googleapis.dev/dotnet/Google.Cloud.Translate.V3/2.0.0/api/…
  • @Iñigo 抱歉,我应该指定这是用 Java 编写的。
  • @JohnHanley 非常感谢。这看起来像我要找的东西。
  • John Hanley 的建议是否解决了您的问题?你已经尝试过了吗?你有什么错误吗?

标签: authentication google-cloud-platform google-translation-api


【解决方案1】:

所以,我终于能够解决这个问题了。

@JohnHanley 不幸的是,TranslationServiceClientBuilder 类在我的环境中不可用。也许它是 DotNet 特定的。不过,这个提示还是很有帮助的,因为我找到了另一个 Builder,它创建了一个 TranslationServiceSettings 的实例,它又具有一个静态工厂方法,该方法又可以用来实例化一个 TranslationServiceClient

以下是有关如何从文件路径到 Google JSON 凭据文件创建 TranslationServiceClient 的完整解决方案。

TranslationServiceSettings settings = TranslationServiceSettings.newBuilder()
    .setCredentialsProvider(new CredentialsProvider() {
    @Override
    public Credentials getCredentials() throws IOException {
        GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(credentialsFileAbsPath))
        .createScoped(Collections.singletonList("https://www.googleapis.com/auth/cloud-platform"));

        return credentials;
        }
    }).build();

TranslationServiceClient translationServiceClient = TranslationServiceClient.create(settings);

当然,匿名类也可以替换为 Lambda 表达式。

@Pjotr​​S 很抱歉造成混乱。我指的文件是 JSON 凭证文件,而不是要翻译的文件。

【讨论】:

  • 很高兴听到您能够解决它。接受这个答案,让这个解决方案更有效。
  • 感谢您的提示,Pjotr​​。完成并接受。 :)
猜你喜欢
  • 2012-09-30
  • 2013-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多