Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authenticate as a service account from Android app for Google Cloud Storage

I have an Android app that will be eventually storing user-generated content in a Google Cloud Storage bucket. But I am unable to do so from my app code. The code looks like this:

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();

I am getting various errors. One of them is:

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

The official documentation simply ignores the use case from an Android app.

like image 865
mnafees Avatar asked Nov 10 '22 23:11

mnafees


1 Answers

I'd suggest to take the responsibility of authorizing the request away from your Android client, as it is not considered a "trustable" client.

A good practice to follow would be to generate a signed URL server side and send that to the client so that the latter can use it to upload files to your buckets in a secure and opaque manner. This way you'll also remove the complexity and exposure to naturally private credentials from your clients.

You can find more about signed URLs in the official docs

like image 110
Jose L Ugia Avatar answered Nov 14 '22 21:11

Jose L Ugia