Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java and Google Spreadsheets API Authorization with OAuth 2.0

I want to read Google Spreadsheets using Java, and the recommended way to do this is using the Google Spreadsheets API.

The problem begins when you want to make procedures secure, so they encourage you to use OAuth 2.0. In the official page they show how to do this using only .NET and say that "the Java client library doesn't currently support OAuth 2.0", and they give alternatives like using OAuth 1.0 or Client Login using directly email and password.

Is this for sure?, isn't there a way to do OAuth 2.0 Authentication through Java, maybe not using directly the Java client library, but through requests with specific parameters.

Please I would appreciate any suggestions.

like image 245
eLRuLL Avatar asked Dec 06 '22 08:12

eLRuLL


1 Answers

I also found it quite silly that the developer docs provided Java examples for everything except OAuth2. Here's some sample code that I used to get it working. For completeness it includes the retrieving spreadsheets example in the later section. Note also that you have to add the required scopes to the Java DrEdit example as shown below.

public class GSpreadsheets {

    private static final String CLIENT_ID = "YOUR_CLIENT_ID";
    private static final String CLIENT_SECRET = "YOUR_SECRET_ID";
    private static final String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";

    public static void main(String[] args) throws Exception {

        if (CLIENT_ID.equals("YOUR_CLIENT_ID") || CLIENT_SECRET.equals("YOUR_SECRET_ID")) {
            throw new RuntimeException(
                    "TODO: Get client ID and SECRET from https://cloud.google.com/console");
        }

            // get credentials similar to Java DrEdit example
            // https://developers.google.com/drive/examples/java
        HttpTransport httpTransport = new NetHttpTransport();
        JsonFactory jsonFactory = new JacksonFactory();

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
                Arrays.asList(DriveScopes.DRIVE, 
                              "https://spreadsheets.google.com/feeds", 
                              "https://docs.google.com/feeds"))
                .setAccessType("online")
                .setApprovalPrompt("auto").build();

        String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
        System.out.println("Please open the following URL in your "
                + "browser then type the authorization code:");
        System.out.println("  " + url);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String code = br.readLine();

        GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
        GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);

            // create the service and pass it the credentials you created earlier
        SpreadsheetService service = new SpreadsheetService("MyAppNameHere");
        service.setOAuth2Credentials(credential);

        // Define the URL to request.  This should never change.
        URL SPREADSHEET_FEED_URL = new URL(
            "https://spreadsheets.google.com/feeds/spreadsheets/private/full");

        // Make a request to the API and get all spreadsheets.
        SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
        List<SpreadsheetEntry> spreadsheets = feed.getEntries();

        // Iterate through all of the spreadsheets returned
        for (SpreadsheetEntry spreadsheet : spreadsheets) {
          // Print the title of this spreadsheet to the screen
          System.out.println(spreadsheet.getTitle().getPlainText());
        }
    }
}
like image 167
Ben Holland Avatar answered Jan 04 '23 22:01

Ben Holland