如何将凭据硬编码到我的 Google 云端硬盘服务,以便应用程序的用户始终可以在没有身份验证的情况下访问我的文件?
我找到了使用 Java SKD 的解决方案,但这些库不适用于 Android:https ://developers.google.com/drive/service-accounts#use_service_accounts_as_application-owned_accounts
有没有成功尝试类似任务的例子?
如何将凭据硬编码到我的 Google 云端硬盘服务,以便应用程序的用户始终可以在没有身份验证的情况下访问我的文件?
我找到了使用 Java SKD 的解决方案,但这些库不适用于 Android:https ://developers.google.com/drive/service-accounts#use_service_accounts_as_application-owned_accounts
有没有成功尝试类似任务的例子?
好的,我找到了解决问题的方法。
当然,我的应用程序是 Android 应用程序,我不想让用户登录/使用任何凭据连接到我的云端硬盘,最后我可以使用默认的云端硬盘网络应用程序操作文件。
实现 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是先前下载的私钥。
允许您的服务从您的云端硬盘访问文件夹:在云端硬盘应用中文件夹的共享选项中,允许用户使用电子邮件:G_SERVICE_EMAIL读/写访问权限。
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;
}
你可能不想这样做。如果您有访问令牌,则始终可以将其作为 URL 参数添加access_token=MY_ACCESS_TOKEN
到请求 URL。