简体   繁体   中英

GoogleCredential Missing Access Token

I am using the service account model and Google's Java API to retrieve and modify users.

I am able to successfully create a GoogleCredential object using code similar to Google's example:

GoogleCredential googleCredential = new GoogleCredentialBuilder()
    .setTransport(httpTransport)
    .setJsonFactory(jsonFactory)
    .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
    .setServiceAccountUser(SERVICE_ACCOUNT_USER)
    .setServiceAccountPrivateKeyFromP12File(P12_PRIVATE_KEY_FILE)
    .setServiceAccountScopes(Collections.singleton(GLOBAL_USER_AND_ALIAS_SCOPE)
    .build();

I see no mention in any examples that I have to explicitly create an access token, so I have been assuming that the above code takes care of that. Is that true?

After that, I successfully create an instance of Directory, then try to retrieve a specific user:

User user = new User();
user = directory.users().get(uid).execute();

That fails, throwing a NullPointerException.

When I inspect the GoogleCredential object right before the call to get the user object, it appears that it does not contain an access token:

accessToken = null
refreshToken = null

What am I missing?

How does one get the access token using the service account model?

Thanks in advance.

Where are you getting your accessToken? Try

credential.refreshToken();
accessToken = credential.getAccessToken();

Also, you should consider running your credentials in the Oauth2 Playground . If it works in the playground, then it's likely something wrong with your implementation.

Andy is correct. The examples for the Google Java API leave out this critical step. At runtime, the Google code throws a NullPointerException with no other details that would identify where it is occurring. Stepping through the debugger in Eclipse made it clear that the token was null in GoogleCredential.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM