I've got a simple Java program that runs on my computer. Its only function is to read an online spreadsheet (which is private - say, a shopping list), then do some unrelated work on that.
Every since Google dropped OAuth1.0 this month, I've been trying to get the program to work with OAuth2. Previously, I could have the program authenticate using my email and an application password.
Now, I was forced to work through access tokens. My code:
package joeslist;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.CellFeed;
import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.gdata.data.spreadsheet.SpreadsheetFeed;
import com.google.gdata.util.ServiceException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author 74
*/
public class JoesList {
public static void main(String[] args) {
final String CLIENT_ID = "my_client_id.apps.googleusercontent.com"; //Unused?
final String CLIENT_SECRET = "myClientSecret";
// This is the Redirect URI for installed applications.
// If you are building a web application, you have to set your
// Redirect URI at https://code.google.com/apis/console.
final String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
final SpreadsheetService service;
CellFeed feed;
service = new SpreadsheetService("Joe's List");
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
String[] SCOPESArray = {"https://spreadsheets.google.com/feeds"};
final List SCOPES = Arrays.asList(SCOPESArray);
GoogleCredential credential;
try {
// Step 1: Authorize.
String authorizationUrl = new GoogleAuthorizationCodeRequestUrl(CLIENT_ID, REDIRECT_URI, SCOPES).build();
// Point or redirect your user to the authorizationUrl.
System.out.println("Go to the following link in your browser:");
System.out.println(authorizationUrl);
// Read the authorization code from the standard input stream.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Paste the code that you got.");
String code = in.readLine();
// End of Step 1 <--
// Step 2: Exchange!
GoogleTokenResponse response
= new GoogleAuthorizationCodeTokenRequest(httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
code, REDIRECT_URI).execute();
System.out.println("Token expires in: " + response.getExpiresInSeconds() + " seconds!");
// Let's build our GoogleCredential now.
credential = new GoogleCredential.Builder()
.setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.build()
.setAccessToken(response.getAccessToken())
.setRefreshToken(response.getRefreshToken());
service.setOAuth2Credentials(credential);
} catch (IOException ex) {
Logger.getLogger(FuckingTest.class.getName()).log(Level.SEVERE, null, ex);
}
try {
final String spreadsheetName = "Joe's sheet";
final URL metafeedUrl=new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full?xoauth_requestor_id=joe");
final SpreadsheetFeed spreadsheetFeed = service.getFeed(metafeedUrl, SpreadsheetFeed.class);
final List<SpreadsheetEntry> spreadsheets = spreadsheetFeed.getEntries();
System.err.println(spreadsheets.size());
for (final SpreadsheetEntry spreadsheet : spreadsheets) {
System.err.println(spreadsheet.getTitle().getPlainText());
if (spreadsheetName.equals(spreadsheet.getTitle().getPlainText())) {
System.err.println("Found the Spreadsheet you want.");
}
}
} catch (final MalformedURLException e) {
throw new RuntimeException(e);
} catch (final IOException | ServiceException e) {
throw new RuntimeException(e);
}
}
}
This is a private little program. I will be its sole user and all I want it to do is read a private spreadsheet.
Will I have to jump through hoops every time I run it, manually copying and pasting the access token? Is there any way I can get a long-lasting or permanent access token?
The answer is that you would have to go through this process every time your access token expires.
Access tokens have limited lifetimes which is correct from a security standpoint. A permanent access token is a security hole waiting to be discovered ( you know someone just forgot to encrypt it and ended up storing it under /var/log or worse on the Desktop).
EDIT based on the comment from OP
Google provides service accounts that allow server to server communications. More information is available at Using OAuth 2.0 for Server to Server Applications
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With