How to Setup DialogFlow V2 Authentication Programmatically with java/android

Prince Francis
1 min readJun 13, 2020

First, you need to download the key json file into your computer from google cloud console.

One simple solution is to export the absolute path of key json file as below

export GOOGLE_APPLICATION_CREDENTIALS=absolute/path/of/key.json

If you are not satisfied with the above solutions, then do it programmatically from java. This is also simple.

  1. add dependencies in gradle file. If you using maven then add the corresponding dependencies in pom.xml
implementation group: 'com.google.api', name: 'gax', version: '1.5.0'
implementation group: 'com.google.cloud', name: 'google-cloud-dialogflow', version: '2.0.0'
implementation group: 'io.grpc', name: 'grpc-core', version: '1.30.0'
implementation group: 'io.grpc', name: 'grpc-api', version: '1.30.0'
implementation group: 'io.grpc', name: 'grpc-okhttp', version: '1.30.0'

2. Authenticate using `GoogleCredentials credentials = GoogleCredentials.fromStream(stream);`

FileInputStream stream = new FileInputStream(new File("/absolute/path/to/key.json"));
GoogleCredentials credentials = GoogleCredentials.fromStream(stream);
String projectId = ((ServiceAccountCredentials)credentials).getProjectId();
SessionsSettings.Builder settingsBuilder = SessionsSettings.newBuilder();
SessionsSettings sessionsSettings = settingsBuilder.setCredentialsProvider(FixedCredentialsProvider.create(credentials)).build();

SessionsClient sessionsClient = SessionsClient.create(sessionsSettings);
String sessionId = UUID.randomUUID().toString();
SessionName session = SessionName.of(projectId, sessionId);

Now start using the session and find intents. Below is a an example.

--

--