zeeshan ansari
zeeshan ansari

Reputation: 381

Getting access token as Null in Google service account

I am using Google service account to get access Token from service side using below code. But I am getting access token as Null. The same returned token will be used to open Google file picker on client side for the same userEmailId. Please suggest what I am doing wrong in my code.

private static final List SCOPE = Arrays.asList("https://www.googleapis.com/auth/drive");

public String getAccessToken(String SERVICE_ACCOUNT_EMAIL, String SERVICE_ACCOUNT_PKCS12_FILE_PATH,String userEmailId){
                try {
                    HttpTransport httpTransport = new NetHttpTransport();
                    JsonFactory jsonFactory = new JacksonFactory();
                    GoogleCredential credential = new GoogleCredential.Builder()
                                                    .setTransport(httpTransport)
                                                    .setJsonFactory(jsonFactory)
                                                    .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
                                                    .setServiceAccountScopes(SCOPE)
                                                    .setServiceAccountUser(userEmailId)
                                                    .setServiceAccountPrivateKeyFromP12File(new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
                                                    .build();

                    credential.getRefreshToken();
                    return credential.getAccessToken();
                } catch (Exception e) {
                    // TODO: handle exception
                    log.severe("Error while getting Drive  credentilas. 5.0"+ e.getMessage());
                    return null;
                }
            }

Upvotes: 0

Views: 6576

Answers (2)

Michael M
Michael M

Reputation: 171

For those using the Firebase Admin SDK, hence the GoogleCredentials class, this will do.

GoogleCredentials credentials = GoogleCredentials.fromStream(serviceAccount).createScoped(Arrays.asList("https://www.googleapis.com/auth/firebase.messaging"));
credentials.refresh();
credentials.getAccessToken();

Upvotes: 10

garyrgilbert
garyrgilbert

Reputation: 487

I had a similar problem. The answer seems to be to simply change from credential.getRefreshToken() to simply credential.refreshToken()

That should solve the issue

Upvotes: 0

Related Questions