Akhil Borkar
Akhil Borkar

Reputation: 41

Google Dialogflow V2 - Authentication - access token

I am using Google Dialogflow V2 API for chatbot design. In order to pass Authorisation header in request parameter of Detect Intent API, I need the access token dynamically.

As per the official documentation, we have to install gcloud on a machine which I don't want.

I want to implement same via java but I am getting an error.

I have followed the link: https://github.com/googleapis/google-auth-library-java and set Environment Variable for GOOGLE_APPLICATION_CREDENTIALS

I have used below Code snippet :

String GoogleCredentialsEnv = System.getenv("GOOGLE_APPLICATION_CREDENTIALS");

GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream("/Users/Downloads/testingbot-29671-d9229dd1e3f9.json"));
    credentials.createScoped(Arrays.asList("https://www.googleapis.com/auth/dialogflow"));

credentials.refreshIfExpired();
AccessToken token = credentials.getAccessToken();

//AccessToken token = credentials.refreshAccessToken();
System.out.println("Token is " + token);

but most of the times I am getting below error

Exception in thread "main" java.io.IOException: Scopes not configured for service account. Scoped should be specified by calling createScoped or passing scopes to constructor.
    at com.google.auth.oauth2.ServiceAccountCredentials.refreshAccessToken(ServiceAccountCredentials.java:363)
    at com.google.auth.oauth2.OAuth2Credentials.refresh(OAuth2Credentials.java:181)
    at com.google.auth.oauth2.OAuth2Credentials.refreshIfExpired(OAuth2Credentials.java:198)
    at com.Model.demo.getBotResponse(demo.java:60)
    at com.Model.demo.main(demo.java:40) 

Upvotes: 4

Views: 3179

Answers (2)

Victor Irechukwu
Victor Irechukwu

Reputation: 81

Try:

GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream("/Users/Downloads/testingbot-29671-d9229dd1e3f9.json"));

if (credentials.createScopedRequired()) {
    credentials = credentials.createScoped(Collections.singletonList("https://www.googleapis.com/auth/dialogflow"));
}

credentials.refreshIfExpired();
AccessToken token = credentials.getAccessToken();

System.out.println(token.getTokenValue());

Upvotes: 4

Prisoner
Prisoner

Reputation: 50701

Make sure the service account you're using has been created for "Dialogflow Integrations".

Upvotes: 0

Related Questions