问题
I was trying to use Google Drive to sync some media files (video/images) and show them in my android app.
I've managed to make it all work fine but according to the docs (or at least from a first read) it looks like there must always be a consent screen where the user, after choosing his google account, agrees with the app getting data from his drive.
The point is that I'd like to 'hardcode' an account that programatically agrees to that since our app is always going to take the media from the same account.
Is that possible??
PD: Don't suggest any other storage service, Drive is a client's requirement.
回答1:
To avoid the user consent, you can use a Service Account.
It's stated in the link that, Google APIs such as the Prediction API and Google Cloud Storage can act on behalf of your application without accessing user information. In these situations your application needs to prove its own identity to the API, but no user consent is necessary. Similarly, in enterprise scenarios, your application can request delegated access to some resources.
For these types of server-to-server interactions you need a service account, which is an account that belongs to your application instead of to an individual end-user. Your application calls Google APIs on behalf of the service account, and user consent is not required. (In non-service-account scenarios, your application calls Google APIs on behalf of end-users, and user consent is sometimes required.)
You can also check this related SO questions for more infor mation.
How to use Google Drive SDK in Android project with hardcoded credentials
Why does Google OAuth2 re-ask user for permission when i send them to auth url again
回答2:
Finally I've managed to make it work altogether:
- Create a service account credential from your google developers console.
- Download your credential in json format.
- Copy the file into assets/res/raw.
- Rename your json into something without weirds chars (Ex: driveserviceprivatekey.json).
List item
InputStream privateJsonStream = dashboardActivity.getResources().openRawResource(R.raw.driveserviceprivatekey); GoogleCredential serviceCredential = GoogleCredential.fromStream(privateJsonStream).createScoped(Arrays.asList(SCOPES));
Now you can use your drive service as follows:
HttpTransport transport = AndroidHttp.newCompatibleTransport(); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); this.mService = new com.google.api.services.drive.Drive.Builder( transport, jsonFactory, null) .setHttpRequestInitializer(credential) .build();
来源:https://stackoverflow.com/questions/37815042/android-google-drive-rest-api-skip-consent-screen-hardcoded-account