What is OAuth2 and things you should know before writing your source code?
OAuth, is an open protocol that aims to standardize the way desktop and web applications access a user's private data. OAuth provides a means of performing API authentication in a standard and secure fashion. As programmers, we're taught to reuse code wherever possible. OAuth will help developers reduce the amount of duplicate code they write and make it easier to create tools that work with multiple services from a variety of different providers.Here are the terms we are using in the OAuth world.
There are three total - one for each step of the OAuth process. Google's OAuth endpoints are:
Obtain a request token: | https://www.google.com/accounts/OAuthGetRequestToken |
Authorize the request token: | https://www.google.com/accounts/OAuthAuthorizeToken |
Upgrade to an access token: | https://www.google.com/accounts/OAuthGetAccessToken |
How to get the required token's from google (OAuth provider) ?
1. First you need to register your application with google api console at this url
https://code.google.com/apis/console
2. Create a new project for your application
3. Create a new OAuth2 Client ID by clicking the button and giving the required information.
4. Then click the create client ID button and that will create a Client ID and Client Secret for your application
How to access google spreadsheet api with a JAVA program?
Here is the complete JAVA source code with comments inside for accessing the google spreadsheet api with the token's you have received from the above step.
package org.samples.oauth2;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.google.gdata.client.GoogleService;
import com.google.gdata.client.authn.oauth.GoogleOAuthHelper;
import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthException;
import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;
import com.google.gdata.client.authn.oauth.OAuthRsaSha1Signer;
import com.google.gdata.client.authn.oauth.OAuthSigner;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.BaseEntry;
import com.google.gdata.data.BaseFeed;
import com.google.gdata.data.Feed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
/**
*
* @author Chanaka Fernando
*
* Class implemented for accessing google spreadsheet application programming interface (API) features related to authentication
*
*/
public class OAuth2Sample {
/**
* Log in to Google, with the OAuth2 authentication
*
* @param clientID client ID received from registering the application with Google
* @param clientSecret client Secret received from registering the application with Google
* @throws AuthenticationException if the service is unable to validate the
* oauth2 parameters.
*/
public void loginOAuth2(String clientID, String clientSecret)
throws AuthenticationException {
String SCOPES = "https://docs.google.com/feeds https://spreadsheets.google.com/feeds";
// STEP 1: Set up the OAuth objects
// You first need to initialize a few OAuth-related objects.
// GoogleOAuthParameters holds all the parameters related to OAuth.
// OAuthSigner is responsible for signing the OAuth base string.
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
// Set your OAuth Consumer Key (which you can register at
// https://www.google.com/accounts/ManageDomains).
oauthParameters.setOAuthConsumerKey(clientID);
// Initialize the OAuth Signer.
OAuthSigner signer = null;
oauthParameters.setOAuthConsumerSecret(clientSecret);
signer = new OAuthHmacSha1Signer();
// Finally create a new GoogleOAuthHelperObject. This is the object you
// will use for all OAuth-related interaction.
GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(signer);
// STEP 2: Get the Authorization URL
// Set the scope for this particular service.
oauthParameters.setScope(SCOPES);
// This method also makes a request to get the unauthorized request token,
// and adds it to the oauthParameters object, along with the token secret
// (if it is present).
try {
oauthHelper.getUnauthorizedRequestToken(oauthParameters);
} catch (OAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Get the authorization url. The user of your application must visit
// this url in order to authorize with Google. If you are building a
// browser-based application, you can redirect the user to the authorization
// url.
String requestUrl = oauthHelper.createUserAuthorizationUrl(oauthParameters);
System.out.println(requestUrl);
System.out.println("Please visit the URL above to authorize your OAuth "
+ "request token. Once that is complete, press any key to "
+ "continue...");
try {
System.in.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// STEP 3: Get the Access Token
// Once the user authorizes with Google, the request token can be exchanged
// for a long-lived access token. If you are building a browser-based
// application, you should parse the incoming request token from the url and
// set it in GoogleOAuthParameters before calling getAccessToken().
String token = null;
try {
token = oauthHelper.getAccessToken(oauthParameters);
} catch (OAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("OAuth Access Token: " + token);
System.out.println();
// STEP 4: Make an OAuth authorized request to Google
// Initialize the variables needed to make the request
URL feedUrl = null;
try {
feedUrl = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Sending request to " + feedUrl.toString());
System.out.println();
SpreadsheetService googleService =
new SpreadsheetService("oauth-sample-app");
// Set the OAuth credentials which were obtained from the step above.
try {
googleService.setOAuthCredentials(oauthParameters, signer);
} catch (OAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Make the request to Google
// Make a request to the API and get all spreadsheets.
SpreadsheetFeed feed = googleService.getFeed(feedUrl, SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
System.out.println("Response Data:");
System.out.println("=====================================================");
if(spreadsheets != null) {
// Iterate through all of the spreadsheets returned
for (SpreadsheetEntry spreadsheet : spreadsheets) {
//Print the name of each spreadshet
System.out.println(spreadsheet.getTitle().getPlainText());
}
}
System.out.println("=====================================================");
System.out.println();
////////////////////////////////////////////////////////////////////////////
// STEP 5: Revoke the OAuth token
////////////////////////////////////////////////////////////////////////////
System.out.println("Revoking OAuth Token...");
try {
oauthHelper.revokeToken(oauthParameters);
} catch (OAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("OAuth Token revoked...");
}
}
With the above code you can access the Google Spreadsheet API with OAuth2 authentication mechanism with your JAVA program.
Cheers !!!!
hey buddy does ur program executed successfully ???????
ReplyDeletethanks..!!
ReplyDeletewhen I registered my android app (installed application) in the google console, google provides only client ID (no cient secret). how should I use this example with no client secret?
ReplyDeleteHey dude, I have tried with your code and I am running into issues.
ReplyDeleteWhat all I did is simply taken your above code and added my client ID and client secret and ran the program. I didn't change anything in the code as I really don't have any idea on connecting to Google drive through Java and also about OAuth authentication..
Issue I am getting when I am running your code is below
I am not able get "oauth_token" as I am getting "com.google.gdata.client.authn.oauth.OAuthException: Error getting HTTP response (response code is 400 I am getting)" exception at "oauthHelper.getUnauthorizedRequestToken(oauthParameters);"..
Help is really appreciated.. :) :)
hey buddy, did you find a solution as i'm having the same problem.
DeleteThis comment has been removed by the author.
DeleteWe working on Core Java Code Examples to make sample codes
ReplyDeleteHave you got anything that allows you to connect to Google spreadsheets using Java? (Basically same as the above but is a working solution?)
DeleteMany thanks in advance.
Hi, the code is unable to generate a authentication url, can you please explain with example what is "scope". Thanks in advance!
ReplyDeleteThis blog is so informative for providing a valuable information about send sms api java.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThank For sharing Valuable Information
ReplyDeleteMulesoft Training in Hyderabad
Mulesoft Online Training in India
I can't help but express how much I adore your post! It's truly remarkable and captures my attention every time, If you're in need of a Debris removal service in Johnstown CO, Bull Elk Junk Removal LLC is here to help.
ReplyDelete