【发布时间】: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 配置:
- 登录https://console.developers.google.com/
- 已创建项目
- 已启用 Gmail API
- 已创建服务帐户(分配的所有者角色)
- 下载 json 凭证文件
- 启用 OAuth 同意屏幕 - 内部(不确定我需要这个,因为我只想访问我的电子邮件)
- 已启用服务帐户域范围的委派(我也不确定是否需要此功能)
【问题讨论】:
-
你想要做什么有点不清楚,而且这段代码不完整。 docs 表示刷新令牌是自动处理的。
-
您好@ChristopherSchneider,感谢您的回复。我用我一直在使用的附加代码更新了我的问题。这是我第一次尝试使用 Google API,所以我只是针对打印标签。就您的观点而言,我试图跳过 refreshToken() 调用,因为 Google 会自动处理,但在调用 execute() 时最终会得到同样的错误。你还有什么我会错过或做错的吗?
-
我对革命/laravel-google-sheets 有同样的问题,您找到解决方案了吗?
-
@Mahefa 您可以在您的 google 配置中添加 'scopes' => [Google_Service_Sheets::DRIVE, Google_Service_Sheets::SPREADSHEETS]
-
@keatwei thks,我会测试一下