Google Dialogflow V2-身份验证-访问令牌

时间:2018-11-26 14:15:19

标签: dialogflow

我正在使用Google Dialogflow V2 API进行聊天机器人设计。 为了在Detect Intent API的request参数中传递Authorization标头,我需要动态访问令牌。

根据官方文档,我们必须在不需要的计算机上安装gcloud。

我想通过Java实现相同功能,但出现错误。

我已遵循以下链接:https://github.com/googleapis/google-auth-library-java并为GOOGLE_APPLICATION_CREDENTIALS设置了环境变量

我在下面的代码段中使用过:

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);

但是大多数时候我都遇到错误了

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) 

2 个答案:

答案 0 :(得分:2)

尝试:

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());

答案 1 :(得分:0)

确保已为“ Dialogflow集成”创建了您正在使用的服务帐户。