首页 > 解决方案 > 如何为 Dialogflow 集成验证 Google 凭据

问题描述

我想将我的 C# 系统与 Google Dialogflow 集成。所以我正在尝试使用 Jon 先生在这里向我展示的代码:

如何使用 API 导入对话流 zip

但我遇到了这个问题:

应用程序默认凭据不可用。如果在 Google Compute Engine 中运行,它们就可用。否则,必须定义环境变量 GOOGLE_APPLICATION_CREDENTIALS 指向定义凭据的文件。有关详细信息,请参阅 https://developers.google.com/accounts/docs/application-default-credentials

我已经下载了我的 Dialogflow 项目服务帐户密钥 JSON 文件。我正在尝试使用此代码进行身份验证:

// Some APIs, like Storage, accept a credential in their Create() method.
// Explicitly use service account credentials by specifying the private key file.
GoogleCredential credential = GoogleCredential.FromFile(theServiceAccountJSONFilePath);
StorageClient storage = StorageClient.Create(credential);
// Make an authenticated API request.
PagedEnumerable<Buckets, Bucket> buckets = storage.ListBuckets(theProjectID);
foreach (Bucket bucket in buckets)
{
    Console.WriteLine(bucket.Name);
}
return null;

我从这个链接得到了那个代码:为服务器到服务器生产应用程序设置身份验证

问题是代码对我来说遇到了这个问题:

dialogflow-ixksso@maintest-vskxxy.iam.gserviceaccount.com 没有 storage.buckets.list 对项目 160007643358 的访问权限。

我在“谷歌云平台”上使用免费选项。也许免费选项不允许以这种方式进行身份验证。

我没有很多这方面的经验,所以任何建议都将不胜感激。

标签: c#google-cloud-platformdialogflow-esgoogle-authentication

解决方案


如注释中所述,大多数情况下最简单的方法是指定GOOGLE_APPLICATION_CREDENTIALS环境变量以引用 JSON 文件。

如果您需要以其他方式加载凭证,您可以使用客户端构建器非常灵活地指定凭证:

来自 ICredential

ICredential credential = LoadCredentialFromSomewhere();
var client = new AgentsClientBuilder
{
    TokenAccessMethod = credential.GetAccessTokenForRequestAsync 
}.Build();

从路径到 JSON 文件

var client = new AgentsClientBuilder
{
    CredentialsPath = "/path/to/serviceaccount.json"
}.Build();

从 JSON 你已经有一个字符串

string json = LoadJsonFromSomewhere();
var client = new AgentsClientBuilder
{
    JsonCredentials = json
}.Build();

推荐阅读