Android Google Cloud Storage with “Client ID for A

2020-02-14 06:44发布

After a lot of reading, I managed to download files from my cloud storage account on android. I had to use the my service account (with the P12 key - which had I had to put into the assets folder), to create the 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 Perfectly! However, this does not prevent any unauthorized Android Application to access my Cloud Storage. So I created a Client ID for Android Application in the Google Console, and gave the proper package name and SHA1 keystore there. Then, I downloaded the JSON client secret and bundled it with the Android App. I then build the ClientSecrets and tried to access the Cloud Storage, but it gives Forbidden response.

Here is the error throwing 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); 

The "getObject.executeMediaAndDownloadTo(out);" thrown the "GoogleAuthException - Forbidden"

The "token" is created in the Android Activity as -

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

The UserRecovrableException is also properly handled -

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

        }

Any help please!

0条回答
登录 后发表回答