【问题标题】:Getting invalid_scope when attempting to obtain a refresh token via the Google API尝试通过 Google API 获取刷新令牌时获取 invalid_scope
【发布时间】:2020-06-09 13:35:12
【问题描述】:

我似乎无法通过 Oauth 使用 Google API。我错过了什么?

错误信息:

com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
  "error" : "invalid_scope",
  "error_description" : "Invalid oauth scope or ID token audience provided."
}

Java 代码:

private void printLabels() {

HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

List<String> scopes = new ArrayList<>();
scopes.add(GmailScopes.GMAIL_LABELS);

GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream("C:\\test\\credential.json"));
credential.createScoped(scopes);
credential.refreshToken();      // error happens here

String appName = "VS";
Gmail.Builder builder = new Gmail.Builder(httpTransport, jsonFactory, credential)
        .setApplicationName(appName);
Gmail gmail = builder.build();

Object o = gmail.users().labels().list("me").execute();
System.out.println("o = " + o);

}

Google API 配置:

  1. 登录https://console.developers.google.com/
  2. 已创建项目
  3. 已启用 Gmail API
  4. 已创建服务帐户(分配的所有者角色)
  5. 下载 json 凭证文件
  6. 启用 OAuth 同意屏幕 - 内部(不确定我需要这个,因为我只想访问我的电子邮件)
  7. 已启用服务帐户域范围的委派(我也不确定是否需要此功能)

【问题讨论】:

  • 你想要做什么有点不清楚,而且这段代码不完整。 docs 表示刷新令牌是自动处理的。
  • 您好@ChristopherSchneider,感谢您的回复。我用我一直在使用的附加代码更新了我的问题。这是我第一次尝试使用 Google API,所以我只是针对打印标签。就您的观点而言,我试图跳过 refreshToken() 调用,因为 Google 会自动处理,但在调用 execute() 时最终会得到同样的错误。你还有什么我会错过或做错的吗?
  • 我对革命/laravel-google-sheets 有同样的问题,您找到解决方案了吗?
  • @Mahefa 您可以在您的 google 配置中添加 'scopes' => [Google_Service_Sheets::DRIVE, Google_Service_Sheets::SPREADSHEETS]
  • @keatwei thks,我会测试一下

标签: java api oauth gmail


【解决方案1】:

credential.createScoped(scopes)

返回具有给定范围的凭证对象的副本。 您可以通过credential.getServiceAccountScopes() 验证这一点,并检查是否设置了范围。

尝试将值分配给凭证对象,例如。

credential = credential.createScoped(scopes);

【讨论】:

    猜你喜欢
    • 2012-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    • 2015-03-05
    • 2015-12-10
    • 2016-10-13
    • 1970-01-01
    相关资源
    最近更新 更多