1

I am working on an application (in Java) which will pull data from GoogleSheets. I am looking to retain the credentials in using Google's StoredCredentials object, however while I have figured out how to create a StoredCredentials object, I can't seem to figure out how to create the Sheets service object using that StoredCredential.

The code I'm using to establish the connection is slightly modified from the Google quick start and is shown below. So, the question is how do you create a connection to GoogleSheets using a StoredCredential object?

Thanks!!

  /**
   * Returns a Google Credential Object which shall be used to authenticate calls to the Google Sheets service
   * @param config The GoogleSheets config
   * @return An authorized Credential
   * @throws IOException in the event of network or other connectivity issues, throws an IOException
   * @throws GeneralSecurityException In the event the credentials are incorrect, throws a Security Exception
   */
  public static Credential authorize(GoogleSheetsStoragePluginConfig config) throws IOException, GeneralSecurityException {
    GoogleClientSecrets clientSecrets = config.getSecrets();
    GoogleAuthorizationCodeFlow flow;
    List<String> scopes = Collections.singletonList(SheetsScopes.SPREADSHEETS);

    flow = new GoogleAuthorizationCodeFlow.Builder
      (GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, clientSecrets, scopes)
        .setDataStoreFactory(new MemoryDataStoreFactory())
        .setAccessType("offline")
        .build();
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
  }

  public static Sheets getSheetsService(GoogleSheetsStoragePluginConfig config) throws IOException, GeneralSecurityException {

    Credential credential = GoogleSheetsUtils.authorize(config);
    StoredCredential storedCredential = config.getStoredCredentials();

    return new Sheets.Builder(
      GoogleNetHttpTransport.newTrustedTransport(), GsonFactory.getDefaultInstance(), credential)
      .setApplicationName("XXX")
      .build();
  }
cgivre
  • 513
  • 4
  • 21
  • Here is a good example of how to store and use credentials: https://stackoverflow.com/a/68702799/11599789 – ziganotschka Jan 05 '22 at 08:16
  • Thanks for the response, but maybe I wasn't quite clear. What happens if I have the refresh or access tokens and want to get the Sheets service? The reason I'm asking is that the app I'm working on (Apache Drill) will be able to obtain and store these creds, but I just need a way to open the servce. Thanks!! – cgivre Jan 05 '22 at 12:57

0 Answers0