我有一个部署到 Tomcat servlet 容器中的应用程序。我有一个后台作业运行,我调用使用服务帐户的 PK12 文件授权的谷歌分析。
我无权访问容器的文件系统,因此我将 pk12 文件部署在 WAR 的 WEB-INF/ 中。我预计不会被授予将任何身份验证密钥添加到 Servlet 容器主机的系统注册表/钥匙串的权限。
GoogleCredential 的 Buidler.setServiceAccountPrivateKeyFromP12File(File) 只需要 java.io.File,所以我最终做了一些难以授权的事情。我使用 serveltContenxt.getResourceAsStream 打开 PK12 文件,并将其内容复制到一个临时文件中,然后将其传递给 Credential 的构建器。
当我试图做
java.io.File p12File = new java.io.File(servletContext.getResource('...pk12.file...').getFile())
出现错误,指出文件不存在,因为它试图打开磁盘上的文件,而 pk12 文件要么未解绑,要么返回的 URI 不是该文件的正确 URI。
这样做的正确方法是什么?我是 PrivateKey 身份验证和谷歌客户端 API 领域的新手。
这是我目前的工作代码:
// create file because credential only takes a File object
final File p12File = File.createTempFile("xxx", ".tmp");
p12File.deleteOnExit();
InputStream in = servletContext.getResourceAsStream("...pk12.file...");
FileOutputStream out = new FileOutputStream(p12File);
org.apache.commons.io.IOUtils.copy(in, out);
out.flush();
out.close();
in.close();
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId("xxxxxxx@developer.gserviceaccount.com")
.setServiceAccountScopes(Collections.singleton(AnalyticsScopes.ANALYTICS_READONLY))
.setServiceAccountPrivateKeyFromP12File(p12File)
.build();
p12File.delete();
// Set up and return Google Analytics API client.
this.analytics = new Analytics.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName("mybackgroundprocess/1.0").build();
谢谢