asp C# 应用程序默认凭据不可用

asp C# Application Default Credentials are not available

我运行正在Google翻译API用C#。 运行 在我的本地计算机上,下一个代码可以运行,但在服务器上联机时会抛出以下错误:

using Google.Cloud.Translation.V2;
TranslationClient client = TranslationClient.Create();
var response = client.TranslateText(sentence, targetLanguage, sourceLanguage: sourceLanguage);

"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."

本地 运行s 只需安装 Cloud SDK Installer 即可完成所有设置,无需在代码中进行身份验证。 在服务器上,我应该使用 OAuth 2.0 还是服务帐户密钥?

有人可以帮助我解决这个问题吗?

编辑:有人可以向我确认是否有必要像这里 https://cloud.google.com/storage/docs/authentication 一样访问本地服务器以在命令行中使用 运行 命令?这将是非常荒谬的,而不是仅仅编写代码。例如 Youtube API 不需要本地访问。

错误信息里都有。你有两个选择

  • 运行 Google 计算机上的 Google Compute Engine 你的程序 运行 并在那里输入你的凭据。

  • 使用服务帐户并设置 "GOOGLE_APPLICATION_CREDENTIALS" 环境变量以引用您的凭据文件(这是一个 .json 文件,您可以从 google 开发者控制台。)

PS:不要将您的凭据文件存储在服务器上可能被其他人访问的任何位置!

您必须从

下载 API 密钥

https://console.developers.google.com/iam-admin/serviceaccounts 之后下载 .P12 文件以在您的代码中使用它

var certificate = new X509Certificate2(@"key3.p12", "notasecret", X509KeyStorageFlags.Exportable); notasecret 是默认密码

为了避免在服务器上进行本地设置,我的问题最简单的答案是使用下面描述的翻译 API 的第三个选项:使用 API 键。 这意味着只是一个简单的 POST 到在 link 中具有 API 键的端点。

https://cloud.google.com/docs/authentication/#getting_credentials_for_server-centric_flow https://cloud.google.com/docs/authentication/api-keys

要生成 JSON 或 PKCS12 格式的私钥:

  1. 在 Google 云平台控制台中打开凭据列表。 OPEN THE LIST OF CREDENTIALS
  2. 单击创建凭据。
  3. Select 服务帐户密钥。 A 创建服务帐户密钥 window 打开。
  4. 单击服务帐户下方的下拉框,然后单击新建服务帐户。
  5. 在名称中输入服务帐户的名称。
  6. 使用默认的服务帐户 ID 或生成一个不同的 ID。
  7. Select 密钥类型:JSON 或 P12.
  8. 点击创建。创建的服务帐户 显示 window 并且密钥类型的私钥 所选内容会自动下载。如果您选择了 P12 键,则 显示私钥密码 ("notasecret")。
  9. 单击“关闭”。

您可以在此处找到更多详细信息 https://cloud.google.com/storage/docs/authentication

按照说明获取 json 文件:

https://cloud.google.com/translate/docs/reference/libraries

然后运行先是这段代码:

System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "c:\mypath\myfile.json");