Custom Integration
Dialogflow Messenger
Integrate Dialogflow with Zoho Live Chat
BotCopy Example Bots

REST API Authentication

In the code snippet above (which makes the call to the REST API), you see an object called httpClient.

This is the object which handles REST API authentication for the website chatbot.

As you know, there are different types of OAuth2 authentication systems we can use, and for this purpose we need to use the service account.

Want to learn Dialogflow’s REST API v2 in depth?

You can learn why the service account is the correct choice for this purpose, along with a systematic introduction to Dialogflow’s REST API v2 in my course.

Here are the steps for performing the REST API authentication:

1 Create a new service account

2 The role should be Dialogflow API Client (API Reader doesn’t provide sufficient permissions, and API Admin provides too many permissions, which can become a problem if your client secret file is ever exposed)

3 Download the client secret file (JSON format) and place it in the same folder as your code

4 Invoke it from your code

You can see my tutorial here which explains how to do steps 1-3. Also, please note that while the tutorial explains how to use the Dialogflow API Admin role, the Dialogflow API Client role is all you need for a website chatbot.

How to use the client secret JSON file to do authentication

The following code snippet is responsible for the authentication:

$client = new \Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes(['https://www.googleapis.com/auth/dialogflow']);
$client->setAuthConfig($secretFile);
$httpClient = $client->authorize();

Here, $secretFile is simply the name of the client secret JSON file, as long as it is placed in the same folder.

To read more about the authentication system I have used here, you can refer to this link. (Read the section titled “Making HTTP Requests directly”)

Tip

Also, using a client secret JSON file does mean there is a chance you might accidentally expose the file contents (web hosts usually treat JSON files like other static HTML files and will not have rules which prevent website visitors from reading its contents). Please make sure you protect the file against unauthorized reads by setting appropriate file permissions from your web host. Having said that, if you only use the Dialogflow API Client role to generate the client secret file, even if someone accidentally gets access to the file, they cannot (say) delete your Dialogflow agent or modify it in some way.

When calling Google APIs from your code, it is easier if you have a good understanding of the overall Google OAuth2 security capabilities. It is ideal if you spend a little time going through the OAuth2 documentation before you build your website chatbot.

>