Android Google Cloud Storage with "Client ID for Android app" prohibited?

After a lot of reading, I was able to download files from my Android cloud storage account. I needed to use my service account (with key P12, which I had to put in the resource folder) to create a GoogleCredential object.

Here is the code -

GoogleCredential credent=new GoogleCredential.Builder() .setTransport(httpTransport) .setJsonFactory(JSON_FACTORY) .setServiceAccountPrivateKey(serviceAccountPrivateKey) .setServiceAccountId(" myservice-account@developer.gserviceaccount.com ").setServiceAccountScopes(Collections.singleton(SCOPE)).build(); Storage client = new Storage.Builder(httpTransport, JSON_FACTORY, credent).setApplicationName("MyStorage").build(); Storage.Objects.Get getObject = client.objects().get("testbucket", "test.jpg"); ByteArrayOutputStream out = new ByteArrayOutputStream(); getObject.getMediaHttpDownloader().setDirectDownloadEnabled(true); getObject.executeMediaAndDownloadTo(out); byte[] result = out.toByteArray(); 

Works great! However, this will not prevent any unauthorized Android application from accessing my cloud storage. Therefore, I created the client identifier for the Android application in the Google console and gave the correct package name and SHA1 storage. Then, I downloaded the JSON client secret and associated it with the Android application. Then I create ClientSecrets and try to access the cloud storage, but it gives a forbidden answer.

Here is the error code:

 AssetManager assetManager; assetManager = context.getAssets(); InputStream inputStream = assetManager.open("client_secret.json"); Reader reader = new InputStreamReader(inputStream); GoogleClientSecrets clientSecrets = null; JsonFactory JSON_FACTORY2 = JacksonFactory.getDefaultInstance(); clientSecrets = GoogleClientSecrets.load(JSON_FACTORY2, reader); GoogleCredential credential=new GoogleCredential.Builder() .setTransport(httpTransport) .setJsonFactory(JSON_FACTORY) .setClientSecrets(clientSecrets) .build().setAccessToken(token); Storage.Objects.Get getObject = client.objects().get("testbucket", "test.jpg"); ByteArrayOutputStream out = new ByteArrayOutputStream(); getObject.getMediaHttpDownloader().setDirectDownloadEnabled(true); getObject.executeMediaAndDownloadTo(out); 

"getObject.executeMediaAndDownloadTo (out);" threw a "GoogleAuthException - Forbidden"

"Token" is created in Android Activity as -

 token = GoogleAuthUtil.getToken(context, email, mScopes); 

UserRecovrableException is also handled correctly -

 catch (UserRecoverableAuthException e) { try { Intent intent = e.getIntent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); return; } 

Any help please!

+3
source share

Source: https://habr.com/ru/post/975076/


All Articles