简体   繁体   中英

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;
                }
            }

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

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();

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