Google Drive/OAuth - Can't figure out how to g

2019-04-05 04:30发布

问题:

I've successfully installed and run the Google Drive Quick Start application called DriveCommandLine. I've also adapted it a little to GET file info for one of the files in my Drive account.

What I would like to do now is save the credentials somehow and re-use them without the user having to visit a web page each time to get an authorization code. I have checked out this page with instructions to Retrieve and Use OAuth 2.0 credentials. In order to use the example class (MyClass), I have modified the line in DriveCommandLine where the Credential object is instantiated:

Credential credential = MyClass.getCredentials(code, "");

This results in the following exception being thrown:

java.lang.NullPointerException
    at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:187)
    at com.google.api.client.json.jackson.JacksonFactory.createJsonParser(JacksonFactory.java:84)
    at com.google.api.client.json.JsonFactory.fromInputStream(JsonFactory.java:247)
    at com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets.load(GoogleClientSecrets.java:168)
    at googledrive.MyClass.getFlow(MyClass.java:145)
    at googledrive.MyClass.exchangeCode(MyClass.java:166)
    at googledrive.MyClass.getCredentials(MyClass.java:239)
    at googledrive.DriveCommandLine.<init>(DriveCommandLine.java:56)
    at googledrive.DriveCommandLine.main(DriveCommandLine.java:115)

I've been looking at these APIs (Google Drive and OAuth) for 2 days now and have made very little progress. I'd really appreciate some help with the above error and the problem of getting persistent credentials in general.

This whole structure seems unnecessarily complicated to me. Anybody care to explain why I can't just create a simple Credential object by passing in my Google username and password?

Thanks, Brian O Carroll, Dublin, Ireland

* Update *

Ok, I've just gotten around the above error and now I have a new one.

The way I got around the first problem was by modifying MyClass.getFlow(). Instead of creating a GoogleClientServices object from a json file, I have used a different version of GoogleAuthorizationCodeFlow.Builder that allows you to enter the client ID and client secret directly as Strings:

flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, "<MY CLIENT ID>", "<MY CLIENT SECRET>", SCOPES).setAccessType("offline").setApprovalPrompt("force").build();

The problem I have now is that I get the following error when I try to use flow (GoogleAuthorizationCodeFlow object) to exchange the authorization code for the Credentials object:

An error occurred: com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
  "error" : "invalid_scope"
}
googledrive.MyClass$CodeExchangeException
        at googledrive.MyClass.exchangeCode(MyClass.java:185)
        at googledrive.MyClass.getCredentials(MyClass.java:262)
        at googledrive.DriveCommandLine.<init>(DriveCommandLine.java:56)
        at googledrive.DriveCommandLine.main(DriveCommandLine.java:115)

Is there some other scope I should be using for this? I am currently using the array of scopes provided with MyClass:

private static final List<String> SCOPES = Arrays.asList(
        "https://www.googleapis.com/auth/drive.file",
        "https://www.googleapis.com/auth/userinfo.email",
        "https://www.googleapis.com/auth/userinfo.profile");

Thanks!

回答1:

I feel your pain. I'm two months in and still getting surprised.

Some of my learnings...

  • When you request user permissions, specify "offline=true". This will ("sometimes" sic) return a refreshtoken, which is as good as a password with restricted permissions. You can store this and reuse it at any time (until the user revokes it) to fetch an access token.

  • My feeling is that the Google SDKs are more of a hinderence than a help. One by one, I've stopped using them and now call the REST API directly.

  • On your last point, you can (just) use the Google clientlogin protocol to access the previous generation of APIs. However this is totally deprecated and will shortly be turned off. OAuth is designed to give fine grained control of authorisation which is intrinsically complex. So although I agree it's complicated, I don't think it's unnecessarily so. We live in a complicated world :-)

Your and mine experiences show that the development community is still in need of a consolidated document and recipes to get this stuff into our rear-view mirrors so we can focus on the task at hand.



回答2:

Oath2Scopes is imported as follows:

import com.google.api.services.oauth2.Oauth2Scopes;

You need to have the jar file 'google-api-services-oauth2-v2-rev15-1.8.0-beta.jar' in your class path to access that package. It can be downloaded here.

No, I don't know how to get Credentials without having to visit the authorization URL at least once and copy the code. I've modified MyClass to store and retrieve credentials from a database (in my case, it's a simple table that contains userid, accesstoken and refreshtoken). This way I only have to get the authorization code once and once I get the access/refresh tokens, I can reuse them to make a GoogleCredential object. Here's how Imake the GoogleCredential object:

GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(jsonFactory)
            .setTransport(httpTransport).setClientSecrets(clientid, clientsecret).build();
    credential.setAccessToken(accessToken);
    credential.setRefreshToken(refreshToken);

Just enter your clientid, clientsecret, accessToken and refreshToken above.

I don't really have a whole lot of time to separate and tidy up my entire code to post it up here but if you're still having problems, let me know and I'll see what I can do. Although, you are effectively asking a blind man for directions. My understanding of this whole system is very sketchy!

Cheers, Brian



回答3:

Ok, I've finally solved the second problem above and I'm finally getting a working GoogleCredential object with an access token and a refresh token.

I kept trying to solve the scopes problem by modifying the list of scopes in MyClass (the one that manages credentials). In the end I needed to adjust the scopes in my modified version of DriveCommandLine (the one that's originally used to get an authorization code). I added 2 scopes from Oauth2Scopes:

GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
    httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
    Arrays.asList(DriveScopes.DRIVE, Oauth2Scopes.USERINFO_EMAIL, Oauth2Scopes.USERINFO_PROFILE))
    .setAccessType("offline").setApprovalPrompt("force").build();

Adding the scopes for user information allowed me to get the userid later in MyClass. I can now use the userid to store the credentials in a database for re-use (without having to get the user to go to a URL each time). I also set the access type to "offline" as suggested by pinoyyid.