无法授权使用谷歌api客户端访问Hangout聊天api。

问题描述 投票:0回答:1

我正在使用google.api.client 1.30.9版本。我想在发送之前使用Hangout Chat Api来验证我的请求。在官方文档中 https:/developers.google.comapi-client-libraryjavagoogle-api-java-clientoauth2。 google曾经使用过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中使用。在使用hangout chat API请求之前,我如何进行身份验证。

java google-api google-oauth google-authentication google-api-java-client
1个回答
1
投票

你说你正在尝试使用服务账户,但你使用的代码是为一个web应用程序设计的,使用Oauth2登录,这将无法与服务账户凭证一起工作,你必须使用正确的代码和正确的凭证类型。

服务账户

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

明确的证书加载

Google auth libray

要从服务账户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();
© www.soinside.com 2019 - 2024. All rights reserved.