如何使用 gcloud 凭据对 Dialogflow API 进行身份验证

2024-05-07

我有一个 Node JS 应用程序,可以向 Dialogflow 代理发出请求。我实际上使用基于临时令牌的请求,但是我如何更改它以通过谷歌服务凭证来做到这一点? (https://cloud.google.com/docs/authentication/getting-started https://cloud.google.com/docs/authentication/getting-started)。我创建了一个凭证(添加了计费)和 service_account json 文件。

我想在节点中使用 Dialogflow 包(https://www.npmjs.com/package/dialogflow https://www.npmjs.com/package/dialogflow)但我不明白如何将它与 json 文件一起使用。

const projectId = 'ENTER_PROJECT_ID_HERE'; 
const sessionId = 'quickstart-session-id';
const query = 'hello';
const languageCode = 'en-US';

// Instantiate a DialogFlow client.
const dialogflow = require('dialogflow');
const sessionClient = new dialogflow.SessionsClient();

// Define session path
const sessionPath = sessionClient.sessionPath(projectId, sessionId);

包的示例使用项目 ID 和会话 ID,但不使用 json 文件,如 google 服务的示例(或使用大查询,如如何使用 json 凭据文件通过 gcloud big query 进行身份验证? https://stackoverflow.com/questions/35529331/how-to-authenticate-with-gcloud-big-query-using-a-json-credentials-file)。不管怎样,我在哪里可以获得这个项目和会话 ID?

请问,是否有人可以帮助我或指导如何以更好的方式做到这一点?谢谢


首先,您必须创建一个服务帐户并下载.JSON本地系统上的凭据格式文件。 现在,可以通过三种方式使用该凭据在对话流库中进行身份验证/授权。

  • Method 1

    创建环境变量GOOGLE_APPLICATION_CREDENTIALS它的值应该是该 JSON 凭据文件的绝对路径。通过这种方法,google 库将隐式加载该文件并使用该凭据进行身份验证。我们不需要在代码中执行与此凭据文件相关的任何操作。

    export GOOGLE_APPLICATION_CREDENTIALS="<absolute-path-of-json-file>" # for UNIX,LINUX
    # then run your code, google library will pick credentials file and loads it automatically
    
  • Method 2

    假设您知道 JSON 文件的绝对路径,并将其作为值放入下面的代码片段中凭证文件路径多变的。

    // You can find your project ID in your Dialogflow agent settings
    const projectId = '<project-id-here>';
    const sessionId = '<put-chat-session-id-here>'; 
    // const sessionid = 'fa2d5904-a751-40e0-a878-d622fa8d65d9'
    const query = 'hi';
    const languageCode = 'en-US';
    const credentials_file_path = '<absolute-file-path-of-JSON-file>';
    
    // Instantiate a DialogFlow client.
    const dialogflow = require('dialogflow');
    
    const sessionClient = new dialogflow.SessionsClient({
      projectId,
      keyFilename: credentials_file_path,
    });
  • Method 3

    您可以记下项目ID, 客户邮箱 and 私钥从 JSON 中,在代码中显式使用它们进行身份验证。

// You can find your project ID in your Dialogflow agent settings
const projectId = '<project-id-here>';
const sessionId = '<put-chat-session-id-here>';
// const sessionid = 'fa2d5904-a751-40e0-a878-d622fa8d65d9'
const query = 'hi';
const languageCode = 'en-US';
const credentials = {
  client_email: '<client-email-here>',
  private_key:
    '<private-key-here>',
};
// Instantiate a DialogFlow client.
const dialogflow = require('dialogflow');

const sessionClient = new dialogflow.SessionsClient({
  projectId,
  credentials,
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 gcloud 凭据对 Dialogflow API 进行身份验证 的相关文章

随机推荐