【问题标题】:400 Bad Request when refreshing token via Gmail Java API通过 Gmail Java API 刷新令牌时出现 400 错误请求
【发布时间】:2020-01-29 13:18:46
【问题描述】:

您好,我正在尝试在我的服务器上使用 Google 的 gmail api 实现发送/接收电子邮件:

private GoogleCredential authorize(HttpTransport httpTransport, JsonFactory jsonFactory ) {
   try{
       Resource resource = new ClassPathResource("my_key_in_json_format.");
       InputStream input = resource.getInputStream();
       GoogleCredential credential = GoogleCredential.fromStream(input);
       credential.createScoped(GmailScopes.all());
       credential.refreshToken();
       return credential;
    }catch(IOException  e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

但是当凭据尝试刷新令牌时,我收到以下异常:

com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
  "error" : "invalid_scope",
  "error_description" : "Bad Request"
}
    at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105)
    at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
    at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
    at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:394)
    at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:493)
    at com.snobo.util.GmailService.authorize(GmailService.java:79)

我尝试将范围参数更改为:

Collection<String> SCOPES = Collections.unmodifiableCollection(Arrays.asList(new String[]{GmailScopes.GMAIL_READONLY}));

刷新令牌时也失败了。 Google 的在线文档对 Java 并不友好。有人遇到类似的问题吗?

【问题讨论】:

  • 我不确定这会解决你的问题,但GoogleCredential is deprecated 你不应该使用它。检查this library
  • 谢谢。我已将其替换为 ServiceAccountCredentials,但仍无法正常工作。

标签: java token gmail-api


【解决方案1】:

我在搜索后找到了基于此线程的问题的答案:

400 Bad Request on Gmail API with php

“如果您只想访问一个帐户(您自己的),则不应使用服务帐户。服务帐户是他们自己的帐户,而不是 Gmail 帐户。它们适用于不需要用户(例如地图、搜索)或当您使用 Google Apps for Work 域并希望为域中的所有用户启用委派时(由域管理员,因此您不需要单独的用户授权)。”

我现在已经修改了我的实现以使用 oauth 网络流。我对 Google 的文档感到非常失望,因为这个问题应该被彻底解决并且尽可能简洁。我确信“服务帐户”和“域范围授权”误导了许多开发人员将服务帐户方法用于多种类型的个人/个人帐户应用程序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 2021-03-22
    • 1970-01-01
    • 2014-10-25
    • 2019-03-10
    相关资源
    最近更新 更多