authentication - 谷歌翻译API V3 : How to authenticate service account from file stream

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

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

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

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

最佳答案

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

@JohnHanley 不幸的是,类(class) TranslationServiceClientBuilder在我的环境中不可用。也许它是 DotNet 特定的。然而,这个提示仍然非常有帮助,因为我发现另一个构建器创建了 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 凭证文件,而不是要翻译的文件。

关于authentication - 谷歌翻译API V3 : How to authenticate service account from file stream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68436263/

相关文章:

javascript - 为什么express.js 无法验证?

ruby-on-rails - 使用 ActiveResource 和 session token 验证请求

mysql - Google CloudSQL 第二代创建功能不起作用

google-cloud-platform - Vertex AI批量预测位置

google-sheets - 有没有办法在电子表格的 'GoogleTranslate()' 函数中跳过翻译中的特定单词?

c# - 如何在 WebApi 中使用 AuthorizationFilterAttribute 与 WebClient 库?

php - 探索数据建模(如何将合理的数据库组合在一起)

docker - 与docker托管实例组,自动堆栈驱动程序日志记录

google-cloud-platform - 谷歌云音译 API

javascript - 如何使用 JavaScript 在我的网站中添加带有自定义标记的语言翻译器?