[英]How to authenticate Google APIs (Google Drive API) from Google Compute Engine and locally without downloading Service Account credentials?
[英]Google translate API V3: How to authenticate service account from file stream
使用 Google Translate V3 API 验证服务帐户的默认方法是通过环境变量。 这个名为 GOOGLE_APPLICATION_CREDENTIALS 的环境变量指向一个带有凭证的 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
唯一的解决方法是将文件复制到环境变量中指定的位置,但这看起来很奇怪,并且在未设置该变量时会失败。
所以,最后,我已经能够解决这个问题。
@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 表达式。
@PjotrS 很抱歉造成混乱。 我所指的文件是 JSON 凭证文件,而不是要翻译的文件。
使用静态构建器创建客户端
TranslationServiceClient client = new TranslationServiceClientBuilder() { CredentialsPath = "C:\\path2urJSON\\ur-credencial.json" }.Build();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.