【问题标题】:Unable to authorize using Google api client to access Hangout chat api无法授权使用 Google api 客户端访问 Hangout 聊天 api
【发布时间】:2020-08-12 03:57:21
【问题描述】:

我正在使用 google.api.client 版本 1.30.9 。我想在发送之前使用 Hangout Chat Api 验证我的请求。在官方文档https://developers.google.com/api-client-library/java/google-api-java-client/oauth2 中,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 聊天 API 请求之前进行身份验证。

【问题讨论】:

标签: java google-api google-oauth google-authentication google-api-java-client


【解决方案1】:

您声明您正在尝试使用服务帐户,但您使用的代码是为使用 Oauth2 登录的 Web 应用程序设计的,这不适用于服务帐户凭据,您必须使用具有正确类型凭据的正确代码。

service account

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

【讨论】:

  • 我从这种方法转向了有问题的方法。使用这种方法,我只能找到使用已弃用的 GoogleCredential 的示例,我宁愿仅在绕过此问题时才使用我的服务帐户进行身份验证。
  • Oauth2 与服务帐户身份验证不同。它自己的库有一个自述文件,其中显示了如何使用服务帐户 github.com/googleapis/google-auth-library-java/blob/master/… 进行身份验证
  • 谢谢我没有遇到这个文档。但是服务帐户身份验证不是 oauth2 的子类型吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-23
  • 1970-01-01
  • 2014-11-18
  • 1970-01-01
  • 2015-06-01
  • 2018-07-11
  • 1970-01-01
相关资源
最近更新 更多