从用于 Google Cloud Storage 的 Android 应用程序验证为服务帐户

Posted

技术标签:

【中文标题】从用于 Google Cloud Storage 的 Android 应用程序验证为服务帐户【英文标题】:Authenticate as a service account from Android app for Google Cloud Storage 【发布时间】:2015-01-05 10:24:26 【问题描述】:

我有一个 android 应用,它最终会将用户生成的内容存储在 Google Cloud Storage 存储桶中。但我无法从我的应用程序代码中这样做。代码如下所示:

JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
KeyStore keystore = SecurityUtils.getPkcs12KeyStore();
keystore.load(resources.openRawResource(R.raw.secret), "***password***".toCharArray()); 
PrivateKey key = (PrivateKey)keystore.getKey("privatekey", "***password***".toCharArray());
credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(new JacksonFactory())
.setServiceAccountPrivateKey(key)
.setServiceAccountId("**************@developer.gserviceaccount.com")
.setServiceAccountScopes(Collections.singleton(StorageScopes.DEVSTORAGE_READ_WRITE))
.build();
credential.refreshToken();
String URI = "https://storage.googleapis.com/"+BUCKET_NAME;
HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
GenericUrl url = new GenericUrl(URI);
HttpRequest request = requestFactory.buildGetRequest(url);
HttpResponse response = request.execute();
String content = response.parseAsString();
Log.d("testing", "response content is: " + content);
new Storage.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName("Doubts").build();

我收到各种错误。其中之一是:

java.security.KeyStoreException: java.security.NoSuchAlgorithmException: KeyStore JKS implementation not found

官方文档只是忽略了 Android 应用中的用例。

【问题讨论】:

binaryking> 即使这行得通 - 你会在你的安卓应用程序中嵌入私钥/密码吗?? 【参考方案1】:

我建议从您的 Android 客户端承担授权请求的责任,因为它不被视为“可信任”客户端。

一个好的做法是生成一个签名的 URL 服务器端并将其发送到客户端,以便后者可以使用它以安全且不透明的方式将文件上传到您的存储桶。通过这种方式,您还可以消除客户对自然私有凭据的复杂性和风险。

您可以在official docs 中找到有关签名 URL 的更多信息

【讨论】:

以上是关于从用于 Google Cloud Storage 的 Android 应用程序验证为服务帐户的主要内容,如果未能解决你的问题,请参考以下文章

Spring + google cloud:没有可用的“com.google.cloud.storage.Storage”类型的合格bean

Google Cloud Storage ACL 不适用于存储桶

从 Google Cloud Function (Python) 将新文件写入 Google Cloud Storage 存储桶

在上载到google cloud storage django之前调整图像大小

从 Cloud Function (python) 写入 Google Cloud Storage

从 Google Cloud Storage 下载数据的更好方法?