【发布时间】:2016-11-07 08:53:40
【问题描述】:
我正在尝试从我的后端访问 Google 表格,它是用 Spring MVC 编写的。使用教程我得到这样的东西:
public static Sheets getSheetsService() throws IOException {
return new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, authorize())
.setApplicationName(APPLICATION_NAME)
.build();
}
public static Credential authorize() throws IOException {
// Load client secrets.
InputStream in =
ConcreteSheetsController.class.getResourceAsStream("/secret.json");
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("offline")
.build();
Credential credential = new AuthorizationCodeInstalledApp(
flow, new LocalServerReceiver()).authorize("user");
System.out.println(
"Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
return credential;
}
秘密的创建方式如下所述:https://developers.google.com/sheets/quickstart/java
这是“工作”,但应用程序的输出为我提供了一个链接。当我点击它时,我的浏览器会要求我选择一个 Google 帐户。如果我这样做一切正常,但我希望有一个更适合服务器的解决方案。我希望我的 secret.json 文件能够让我的应用程序在不提供我自己的用户帐户的情况下登录。有什么办法可以做到吗?
【问题讨论】:
-
您可以尝试在使用OAuth 2.0 for Server to Server Applications 中查看服务帐户。您可以进行 API 调用,尤其是在调用 Cloud API 以访问基于项目的数据而不是特定于用户的数据时。
-
你应该在生成credentials.json的时候选择了'Web server',这里有个地方放redirect url
标签: java google-sheets google-api google-sheets-api