How authenticate with gcloud credentials an Dialogflow API

六月ゝ 毕业季﹏ 提交于 2019-12-06 11:17:24

First you have to create a service account and download a .JSON format file of credentials on your local system. Now, there are three ways to use that credentials for authentication/authorisation in dialogflow library.

  • Method 1

    Create a environment variable GOOGLE_APPLICATION_CREDENTIALS and it's value should be the absolute path of that JSON credentials file.By this method, google library will implicitly loads the file and use that credentials for authentication. We don't need to do anything inside our code relating to this credentials file.

    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

    Assume, you know the absolute path of your JSON file and put that as value in below snippet of credentials_file_path variable.

    // 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

    You can note down the project_id, client_email and private_key from the JSON, use them in your code for authentication explicitly.

// 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,
});

Here is how you can do it with a service account code sample is in kotlin and definitely can be translated into the node.js sdk

    val credentialsProvider = FixedCredentialsProvider.create(ServiceAccountCredentials
            .fromStream(Classes.getResourceAsStream([YOUR JSON CONFIG FILE GOES HERE])))
    val sessionsSettings = SessionsSettings.newBuilder().setCredentialsProvider(credentialsProvider).build()
    sessionsClient = SessionsClient.create(sessionsSettings)

You can get the service account from Dialogflow settings click on the service account links and then create a json config file there in ur cloud console.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!