0

我有一个部署到 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();

谢谢

4

1 回答 1

1

我发现这里回答了同样的问题: Getting a PrivateKey object from a .p12 file in Java

我只需要从资源中创建一个私钥

InputStream in = servletContext.getResourceAsStream("p12.file");
PrivateKey privateKey = SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(), in, "notasecret", "privatekey", "notasecret");

然后打电话

GoogleCredential.Builder.setServiceAccountPrivateKey(PrivateKey privateKey)
于 2014-10-08T22:16:26.227 回答