Question

I've seen too many questions in here (SO) asking about OAuth and how to connect to Facebook Graph API or Twitter API using OAuth protocol.

I've discovered JOAuth (from Google Code) and I was wondering how can I use it? What other features does JOAuth provide and does it fare well with other java oauth libraries?

Was it helpful?

Solution

Seeing that I've written JOAuth, I thought it would be appropriate to answer this question on SO. I didn't find the option to make this question a community wiki. :(

Note I'm not here to discuss OAuth Authorization. There are various sites dedicated for this.

JOAuth comes with a wonderful feature. It has a controller OAuthServlet that manages your HTTP Redirect response from the Service provider. The way to configure OAuthServlet to your web application, simply declare it as a <servlet> in your web.xml like so:

 <servlet>
  <description>An OAuth Servlet Controller</description>
  <display-name>OAuthServlet</display-name>
  <servlet-name>OAuthServlet</servlet-name>
  <servlet-class>com.neurologic.oauth.servlet.OAuthServlet</servlet-class>
  <init-param>
   <param-name>config</param-name>
   <param-value>/WEB-INF/oauth-config.xml</param-value>
  </init-param>
  <load-on-startup>3</load-on-startup>
 </servlet>

And your servlet mapping:

 <servlet-mapping>
  <servlet-name>OAuthServlet</servlet-name>
  <url-pattern>/oauth/*</url-pattern>
 </servlet-mapping>

Now, that you have an OAuth servlet setup (bear in mind that <load-on-startup> isn't necessary but I like to have my servlets initialized before I use it), let's talk about configuring JOAuth.

The default JOAuth configuration file is /WEB-INF/oauth-config.xml (hence it doesn't have to be <init-param> in your servlet declaration). The configuration file looks as follows:

<?xml version="1.0" encoding="UTF-8"?>
<oauth-config>
 <!-- Twitter OAuth Config -->
 <oauth name="twitter" version="1">
  <consumer key="TWITTER_KEY" secret="TWITTER_SECRET" />
  <provider requestTokenUrl="https://api.twitter.com/oauth/request_token" authorizationUrl="https://api.twitter.com/oauth/authorize" accessTokenUrl="https://api.twitter.com/oauth/access_token" />
 </oauth>

 <!-- Facebook OAuth -->
 <oauth name="facebook" version="2">
  <consumer key="APP_ID" secret="APP_SECRET" />
  <provider authorizationUrl="https://graph.facebook.com/oauth/authorize" accessTokenUrl="https://graph.facebook.com/oauth/access_token" />
 </oauth>

 <service path="/request_token_ready" class="com.neurologic.music4point0.oauth.TwitterOAuthService" oauth="twitter">
  <success path="/start.htm" />
 </service>

 <service path="/oauth_redirect" class="com.neurologic.music4point0.oauth.FacebookOAuthService" oauth="facebook">
  <success path="/start.htm" />
 </service>
</oauth-config>

You'll notice that each <oauth> element has a version attribute (it's a compulsory attribute that's needed by the controller to know which oauth flow to use). These only have 2 possible values (1 for OAuth1 and 2 for OAuth 2). For OAuth 2, the <consumer> element doesn't have the requestTokenUrl attribute like its version 1 counterpart.

The OAuth Service is the one responsible for the OAuth handling. Each OAuthService is called by the controller through the execute() method. There are 2 types of OAuthService:

  • com.neurologic.oauth.service.impl.OAuth1Service.
  • com.neurologic.oauth.service.impl.OAuth2Service.

Note For each service, if you're using OAuth 2, you must have a service that extends OAuth2Service. The same applies for OAuth 1. Failure to do that results in an exception being thrown.

Each <service> tag must have a name attribute that matches the <oauth> name attribute (Case sensitive).

Both OAuth1Service and OAuth2Service execute(HttpServletRequest, HttpServletResponse) have been implemented to best handle the flow of the OAuth authorization protocol, but you can override it if you're not happy with it.

An example of the com.neurologic.music4point0.oauth.FacebookOAuthService:

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.oauth.enums.GrantType;
import net.oauth.exception.OAuthException;
import net.oauth.parameters.OAuth2Parameters;

import com.neurologic.oauth.service.impl.OAuth2Service;
import com.neurologic.oauth.util.Globals;

/**
 * @author The Elite Gentleman
 * @since 05 December 2010
 *
 */
public class FacebookOAuthService extends OAuth2Service {

 private static final String REDIRECT_URL = "http://localhost:8080/Music4Point0/oauth/oauth_redirect";

 /* (non-Javadoc)
  * @see com.neurologic.oauth.service.impl.OAuth2Service#processReceivedAuthorization(javax.servlet.http.HttpServletRequest, java.lang.String, java.util.Map)
  */
 @Override
 protected String processReceivedAuthorization(HttpServletRequest request, String code, Map<String, String> additionalParameters) throws OAuthException {
  // TODO Auto-generated method stub
  OAuth2Parameters parameters = new OAuth2Parameters();
  parameters.setCode(code);
  parameters.setRedirectUri(REDIRECT_URL);

  Map<String, String> responseMap = getConsumer().requestAcessToken(GrantType.AUTHORIZATION_CODE, parameters, null, (String[])null);
  if (responseMap == null) {
   //This usually should never been thrown, but we just do anyway....
   throw new OAuthException("No OAuth response retrieved.");
  }

  if (responseMap.containsKey("error")) {
   throwOAuthErrorException(responseMap);
  }

  if (responseMap.containsKey(OAuth2Parameters.ACCESS_TOKEN)) {
   String accessToken = responseMap.remove(OAuth2Parameters.ACCESS_TOKEN);
   request.getSession().setAttribute(Globals.SESSION_OAUTH2_ACCESS_TOKEN, accessToken);
   processAdditionalReceivedAccessTokenParameters(request, responseMap);
  }

  return null;
 }

 /* (non-Javadoc)
  * @see com.neurologic.oauth.service.impl.OAuth2Service#processAdditionalReceivedAccessTokenParameters(javax.servlet.http.HttpServletRequest, java.util.Map)
  */
 @Override
 protected void processAdditionalReceivedAccessTokenParameters(HttpServletRequest request, Map<String, String> additionalParameters) throws OAuthException {
  // TODO Auto-generated method stub

 }
}

Since Facebook still uses OAuth 2 draft 0 (zero), their access token doesn't do an HTTP 302 redirect, and that's why processReceivedAuthorization() is returns a null. The processReceivedAuthorization() method allows the client to process received autorization code and expects an authorization URL (that's why it expects a return type of String). If the method returns a null or an empty string, a url redirect never occurs.

Once the oauth flow has completed, the path in the <success> element is then called (through a RequestDispatcher), to show that OAuth is successfully completed.

To access the Access Token, (after successful logon via OAuth), do the following:

AccessToken accessToken = (AccessToken)request.getSession().getAttribute(Globals.SESSION_OAUTH1_ACCESS_TOKEN); //For OAuth 1 access token
String accessToken = (String)request.getSession().getAttribute(Globals.SESSION_OAUTH2_ACCESS_TOKEN); //For OAuth 2 access token.

I hope this little example helps those who are keen in making OAuth a worthwile experience for their development.

Sorry that I couldn't find the community wiki checkbox. Visit my blog (which has almost nothing on it) when you have time.

Adieu :-)

PS This is an implementation of the TwitterOAuthService:

import javax.servlet.http.HttpServletRequest;

import net.oauth.exception.OAuthException;
import net.oauth.signature.impl.OAuthHmacSha1Signature;
import net.oauth.token.AccessToken;
import net.oauth.token.AuthorizedToken;
import net.oauth.token.RequestToken;

import com.neurologic.oauth.service.impl.OAuth1Service;

/**
 * @author The Elite Gentleman
 * @since 05 December 2010
 *
 */
public class TwitterOAuthService extends OAuth1Service {

    public static final String REQUEST_TOKEN_SESSION = "TWITTER_REQUEST_TOKEN_SESSION";

    /* (non-Javadoc)
     * @see com.neurologic.oauth.service.impl.OAuth1Service#processReceivedAuthorizedToken(javax.servlet.http.HttpServletRequest, net.oauth.token.AuthorizedToken)
     */
    @Override
    protected AccessToken processReceivedAuthorizedToken(HttpServletRequest request, AuthorizedToken authorizedToken) throws OAuthException {
        // TODO Auto-generated method stub
        String requestTokenSecret = null;
        RequestToken requestToken = (RequestToken) request.getSession().getAttribute(REQUEST_TOKEN_SESSION);

        if (requestToken != null) {
            requestTokenSecret = requestToken.getTokenSecret();
        }

        return getConsumer().requestAccessToken(null, authorizedToken, requestTokenSecret, new OAuthHmacSha1Signature());
    }
}

Additional Resources

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top