0

I have a service account and want to share its credentials to the api.

I tried https://developers.google.com/identity/protocols/oauth2/service-account , but it seems like import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; is deprecated.

Is the java quickstart credentials supposed to be an alternative to the import? I'm not exactly sure how to get credentials passed in.

Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
                .setApplicationName(APPLICATION_NAME)
                .build();

1 Answers1

0

You are correct, the GoogleCredential is currently deprecated. Instead, if you need to access Google Sheets using a service account, use the Google OAuth2 library.

Usage example:


private static final String APPLICATION_NAME = "The Sheets API";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final List<String> SCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS_READONLY);

final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredentials googleCredentials;
try(InputStream inputSteam = <YOURCLASS>.class.getResourceAsStream("/path/to/credentials/file.json")) {
  googleCredentials = GoogleCredentials.fromStream(credentialsStream).createScoped(SCOPES)
}
Sheets service = Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpCredentialsAdapter(googleCredentials))
            .setApplicationName(APPLICATION_NAME)
            .build()

You can also find an excellent explanation from this thread

  • what is credentialsStream supposed to be? Is this an import? tia! – apitester Mar 15 '22 at 21:26
  • Here is the sample on where the credentiaslStream are in this [link](https://github.com/googleapis/google-auth-library-java/blob/f9a9b8ace0199e6b75ed42c7bacfa3be30c34111/oauth2_http/java/com/google/auth/oauth2/GoogleCredentials.java) – Ricardo Jose Velasquez Cruz Mar 15 '22 at 21:40