我使用Watson APIs Java SDK并且我的身份验证使用函数 setUsernameAndPassword(username, password),但现在我想使用Tokens 进行身份验证。
我的“用户名和密码”代码
mAssistant = new Assistant("2018-02-16");
mAssistant.setUsernameAndPassword(mUserName, mPassword);
InputData input = new InputData.Builder("Hello").build();
MessageOptions options = new MessageOptions.Builder("{workspaceId}")
.input(input)
.build();
MessageResponse response = mAssistant.message(options).execute();
System.out.println(response);
它工作正常。
我使用这种方法来获取我的令牌。
curl -X GET --user "{username}:{password}" "https://gateway.watsonplatform.net/authorization/api/v1/token?url=https://gateway.watsonplatform.net/conversation/api"
用于身份验证Method-1 的令牌
mAssistant = new Assistant("2018-02-16");
Map<String, String> map = new HashMap<>();
map.put("X-Watson-Authorization-Token", "{token_string}");
mAssistant.setDefaultHeaders(map);
mAssistant.setSkipAuthentication(true);
InputData input = new InputData.Builder("Hello").build();
MessageOptions options = new MessageOptions.Builder("{workspaceId}")
.input(input)
.build();
MessageResponse response = mAssistant.message(options).execute();
System.out.println(response);
获取错误代码
E/WatsonService: POST status: 403, error: Forbidden
com.ibm.watson.developer_cloud.service.exception.ForbiddenException: Forbidden
05-07 16:05:57.720 10392-10476/mvi.rcu W/System.err: at com.ibm.watson.developer_cloud.service.WatsonService.processServiceCall(WatsonService.java:401)
05-07 16:05:57.720 10392-10476/mvi.rcu W/System.err: at com.ibm.watson.developer_cloud.service.WatsonService$WatsonServiceCall.execute(WatsonService.java:459)
方法二
mAssistant = new Assistant("2018-02-16");
IamOptions options = new IamOptions.Builder()
.accessToken(token)
.build();
mAssistant.setIamCredentials(options);
mAssistant.setEndPoint("https://gateway.watsonplatform.net/conversation/api");
// do same ...
// mAssistant.message(options).execute();
// ...
得到错误信息
W/System.err: com.ibm.watson.developer_cloud.service.exception.UnauthorizedException: Unauthorized: Access is denied due to invalid credentials. Tip: Did you set the Endpoint?
W/System.err: at com.ibm.watson.developer_cloud.service.WatsonService.processServiceCall(WatsonService.java:398)
W/System.err: at com.ibm.watson.developer_cloud.service.WatsonService$WatsonServiceCall.execute(WatsonService.java:459)
如果我想通过Watson APIs Java SDK使用 Tokens 进行身份验证,我应该怎么做?