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