Android GoogleCredential Debug vs Release

2019-06-04 20:54发布

问题:

I am trying to read my GCS bucket but am seeing an interesting behavior. When running my app through Android Studio (as Debug variant) I am able to download objects. When I create a Signed APK (or run as Release variant) I am no longer able to download object and receive a 404 error.

This is my authorization method:

GoogleCredential googleCredential = null;
JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
HttpTransport httpTransport = AndroidHttp.newCompatibleTransport();

/** Authorizes the installed application to access user's protected data. */
public GoogleCredential authorize() throws Exception {
    String p12Password = "****";
    String keyAlias = "****";
    KeyStore keystore = KeyStore.getInstance("PKCS12");
    keystore.load(getResources().openRawResource(R.raw.gcskeystore), p12Password.toCharArray());

    PrivateKey privateKey = (PrivateKey)keystore.getKey(keyAlias, p12Password.toCharArray());

    Set<String> scopes = new HashSet<String>();
    scopes.add(StorageScopes.DEVSTORAGE_READ_WRITE);

    String emailAddress = "********@developer.gserviceaccount.com";

    GoogleCredential credential = new GoogleCredential.Builder()
            .setTransport(httpTransport)
            .setJsonFactory(JSON_FACTORY)
            .setServiceAccountId(emailAddress)
            .setServiceAccountPrivateKey(privateKey)
            .setServiceAccountScopes(scopes)
            .build();

    return credential;
}

Printing out my credential, it looks like this when running:

com.google.api.client.googleapis.auth.oauth2.GoogleCredential@42ed8060

and this when I receive an error:

bpr@46096240

Since the issue occurs when creating a signed release I thought my proguard-rules are tripping something up but the only line I have added is:

-dontwarn sun.misc.*

Hopefully someone has seen this type of behavior before! Any help would be greatly appreciated!!

Jenny

回答1:

I was able to fix my issue. I dug into the proguard-rules a little bit more. Making this update resolved my problem:

# Needed to keep generic types and @Key annotations accessed via reflection

-keepattributes Signature,RuntimeVisibleAnnotations,AnnotationDefault

-keepclassmembers class * {
  @com.google.api.client.util.Key <fields>;
}

# Needed by Guava
# See https://groups.google.com/forum/#!topic/guava-discuss/YCZzeCiIVoI

-dontwarn sun.misc.Unsafe
-dontwarn com.google.common.collect.MinMaxPriorityQueue

# Needed by google-http-client-android when linking against an older platform version

-dontwarn com.google.api.client.extensions.android.**

# Needed by google-api-client-android when linking against an older platform version

-dontwarn com.google.api.client.googleapis.extensions.android.**