2

如何将凭据硬编码到我的 Google 云端硬盘服务,以便应用程序的用户始终可以在没有身份验证的情况下访问我的文件?

我找到了使用 Java SKD 的解决方案,但这些库不适用于 Android:https ://developers.google.com/drive/service-accounts#use_service_accounts_as_application-owned_accounts

有没有成功尝试类似任务的例子?

4

2 回答 2

3

好的,我找到了解决问题的方法。

当然,我的应用程序是 Android 应用程序,我不想让用户登录/使用任何凭据连接到我的云端硬盘,最后我可以使用默认的云端硬盘网络应用程序操作文件。

  1. 需要采取措施:创建服务帐户,如 例所示。
  2. 下载私钥API 访问站点并将其放在例如。在资产文件夹中。
  3. 下载并导入这些库:
    • google-api-client-1.13.2-beta.jar
    • google-api-client-android-1.13.2-beta.jar
    • google-api-services-drive-v2-rev60-1.13.2-beta.jar
    • google-http-client-1.13.1-beta.jar
    • google-http-client-android-1.13.1-beta.jar
    • google-http-client-gson-1.13.1-beta.jar
    • google-http-client-jackson2-1.13.1-beta.jar
    • google-oauth-client-1.13.1-beta.jar
    • gson-2.1.jar
    • 番石榴-jdk5-13.0.jar
    • 杰克逊核心2.0.5.jar
    • jsr305-1.3.9.jar
  4. 实现 Drive 服务获取器:

    public Drive getDriveService() throws GeneralSecurityException, IOException, URISyntaxException {
        HttpTransport httpTransport = new NetHttpTransport();
        JacksonFactory jsonFactory = new JacksonFactory();
        GoogleCredential credential = new GoogleCredential.Builder()
            .setTransport(httpTransport)
            .setJsonFactory(jsonFactory)
            .setServiceAccountId(G_SERVICE_EMAIL)
            .setServiceAccountScopes(DriveScopes.DRIVE)
            .setServiceAccountPrivateKeyFromP12File(PKC_12_FILE)
            .build();
        Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
            .setHttpRequestInitializer(credential)
            .build();
        return service;
    }
    

    其中G_SERVICE_EMAIL是来自API 访问站点的电子邮件地址,而PKC_12_FILE是先前下载的私钥。

  5. 允许您的服务从您的云端硬盘访问文件夹:在云端硬盘应用中文件夹的共享选项中,允许用户使用电子邮件:G_SERVICE_EMAIL读/写访问权限。

    PKC 文件集成

    private File getTempPkc12File() throws IOException {
        InputStream pkc12Stream = getAssets().open("this-is-your-unique-hash-privatekey.p12");
        File tempPkc12File = File.createTempFile("temp_pkc12_file", "p12");
        OutputStream tempFileStream = new FileOutputStream(tempPkc12File);
    
        int read = 0;
        byte[] bytes = new byte[1024];
        while ((read = pkc12Stream.read(bytes)) != -1) {
            tempFileStream.write(bytes, 0, read);
        }
        return tempPkc12File;
    }
    
于 2013-03-24T17:47:06.120 回答
0

你可能不想这样做。如果您有访问令牌,则始终可以将其作为 URL 参数添加access_token=MY_ACCESS_TOKEN到请求 URL。

于 2013-03-24T00:48:38.333 回答