我正在使用google.api.client版本1.30.9。我想在发送前使用环聊聊天Api对我的请求进行身份验证。 Google在官方文档https://developers.google.com/api-client-library/java/google-api-java-client/oauth2中使用了GoogleCredential,但现在已弃用。我正在使用以下代码来获取可用于构建HangoutChat对象的经过身份验证的凭据对象。
private static Credential authorize() throws Exception {
httpTransport=GoogleNetHttpTransport.newTrustedTransport();
dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
// load client secrets
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
new InputStreamReader(HangoutsChat.class.getResourceAsStream("/client_secrets.json")));
// set up authorization code flow
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, JSON_FACTORY, clientSecrets,
Collections.singleton(HangoutsChat.DEFAULT_BASE_URL)).setDataStoreFactory(dataStoreFactory)
.build();
// authorize
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
AuthorizationCodeInstalledApp和LocalServerReceiver,在最新版本的google API中不可用。在请求使用环聊聊天API之前如何进行身份验证。
答案 0 :(得分:1)
您声明您正在尝试使用服务帐户,但您使用的代码是为Web应用程序设计的,以使用Oauth2登录,因此这不适用于服务帐户凭据,您必须使用具有corect凭据类型的正确代码。
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
...
// Build service account credential.
GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream("MyProject-1234.json"))
.createScoped(Collections.singleton(PlusScopes.PLUS_ME));
// Set up global Plus instance.
plus = new Plus.Builder(httpTransport, jsonFactory, credential)
.setApplicationName(APPLICATION_NAME).build();
...
要从服务帐户JSON密钥获取凭据,请使用GoogleCredentials.fromStream(InputStream)或GoogleCredentials.fromStream(InputStream,HttpTransportFactory)。请注意,必须先刷新凭据,然后才能使用访问令牌。
GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream("/path/to/credentials.json"));
credentials.refreshIfExpired();
AccessToken token = credentials.getAccessToken();
// OR
AccessToken token = credentials.refreshAccessToken();