Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get access token from GoogleCredential?

I am trying to get an access token to use the Google Play Android Developer API, and I got this far using the Google API Java Client documentation example:

HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); JsonFactory JSON_FACTORY = new JacksonFactory();  GoogleCredential credential = new GoogleCredential.Builder()     .setTransport(HTTP_TRANSPORT)     .setJsonFactory(JSON_FACTORY)     .setServiceAccountId("...gserviceaccount.com")     .setServiceAccountScopes("https://www.googleapis.com/auth/androidpublisher")     .setServiceAccountPrivateKeyFromP12File(keyFile)     .build(); 

But how do I get the access token from this credential? credential.getAccessToken() returns null. Am I doing something wrong, or missing some steps?

like image 740
Kalina Avatar asked Sep 24 '12 22:09

Kalina


People also ask

How do I get an access token from an authorization server?

After you add the authorization profile, you need to get access token from the server. In this tutorial, we get it by using the Authorization Code grant method: Click Get Token. In the subsequent dialog, enter Client Identification and Secret, Authorization URI, Access Token URI and Redirect URI.

How do I get the access token from refresh token?

To get an access token using a refresh token, you must first get the refresh token. Then you use the refresh token from then on to generate an access token.

How can I get access token authorization code?

The authorization code grant is used when an application exchanges an authorization code for an access token. After the user returns to the application via the redirect URL, the application will get the authorization code from the URL and use it to request an access token.


2 Answers

Got it. You have to call credential.refreshToken() before credential.getAccessToken(). It doesn't say this anywhere in the documentation but that's what does it.

credential.refreshToken(); accessToken = credential.getAccessToken(); 
like image 91
Kalina Avatar answered Oct 23 '22 04:10

Kalina


If you use ServiceAccountCredentials.fromStream() to create your credential object, you may have to call the createScoped() method too.

    FileInputStream fileInputStream = new FileInputStream(KEY_FILE_PATH);     GoogleCredentials credentials = ServiceAccountCredentials.fromStream(fileInputStream);     credentials = credentials.createScoped(SCOPES);     AccessToken accessToken = credentials.refreshAccessToken(); 

Otherwise you get the error

java.io.IOException: Scopes not configured for service account. Scoped should be specified by calling createScoped or passing scopes to constructor.

like image 21
lordofmax Avatar answered Oct 23 '22 04:10

lordofmax