2

I tried to follow the instructions on JOAuth, a java-based OAuth 1 (final) and OAuth 2 (draft 10) library. How do I use it? in order to fetch facebook access token but with no success.

i did the following:

added these lines to WEB-INF/web.xml

<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>
<servlet-mapping>
 <servlet-name>OAuthServlet</servlet-name>
 <url-pattern>/oauth/*</url-pattern>
</servlet-mapping>

created WEB-INF/oauth-config.xml with the following lines: (renamed app key and secret to <APP_KEY> and <APP_SECRET>)

<?xml version="1.0" encoding="UTF-8"?>
<oauth-config>
<oauth name="facebook" version="2">
 <consumer key="<APP_KEY>" secret="<APP_SECRET>" />
 <provider authorizationUrl="https://graph.facebook.com/oauth/authorize" 
   accessTokenUrl="https://graph.facebook.com/oauth/access_token" />
</oauth>

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

my com.facebook.FacebookOAuthService class ( The OAuth Service ):

package com.xpogames.facebook;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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://127.0.0.1:5080/Red5FacebookAuth/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#processAdditionalReceivedAccessTokenParamet    ers(javax.servlet.http.HttpServletRequest, java.util.Map)
  */
 @Override
 protected void processAdditionalReceivedAccessTokenParameters(HttpServletRequest request, Map<String, String> additionalParameters) throws OAuthException {
  // TODO Auto-generated method stub

 }   
}

and finally the start.jsp file that the user should be forwarded to on success.

<%@page import="com.neurologic.oauth.util.Globals"%>

<% 
String accessToken =     (String)request.getSession().getAttribute(Globals.SESSION_OAUTH2_ACCESS_TOKEN); //For OAuth 2 access token.
%>
<%= accessToken %>

when I try to test it by forwarding my browser to http://127.0.0.1:5080/Red5FacebookAuth/oauth/oauth_redirect the output that i get is null which means that the attribute does not exist

there are no errors but still i get no proper token.

I'm new to tomcat and the servlet configuration so i might have missed something.

what am i missing?

thanks a lot!

2
  • 1
    Thanks for the feedback, I'm busy answering this. Btw. If you checked on Google Code, v1.1 of the JOAuth is out. Commented Mar 14, 2011 at 20:06
  • Thanks for detailed information. but, i am getting one error while executing above code. Error is : Cannot find the declaration of element 'oauth-config'. [2]. can u tell me why this error came? Commented Jul 10, 2012 at 18:02

1 Answer 1

4

Ok, what I never answered before (because I assumed the user to know OAuth Authorization) is the initiation of the OAuth Authorization flow.

Firstly, follow the OAuth flow as stipulated here. I'm showing you how it's done in java based on what's documented.

For this workflow to work, you need to request an Authorization Code (through Authorization Request as mentioned in paragraph 4.1.1 of OAuth Specification).

That method is called from OAuth2Consumer class:

public String generateRequestAuthorizationUrl(ResponseType responseType, String redirectUri, String state, String scopeDelimiter, String... scope) throws OAuthException {

Remember, scopeDelimiter for Facebook is a comma , and responseType is ResponseType.CODE. scope is what Facebook perceives as permissions.

A full example is this:

String client_id = "<APP_ID>";
String client_secret = "<CLIENT_SECRET>";
String redirectUrl = "http://127.0.0.1:5080/Red5FacebookAuth/oauth/oauth_redirect"; 
OAuth2ServiceProvider provider = new OAuth2ServiceProvider("https://graph.facebook.com/oauth/authorize", "https://graph.facebook.com/oauth/access_token");
OAuth2Consumer consumer = new OAuth2Consumer(client_id, client_secret, provider);


//Using HttpServletResponse (but you can kickstart it through an Action/Controller/etc.
response.sendRedirect(consumer.generateRequestAuthorizationUrl(ResponseType.CODE, redirectUrl, null, ",", (String[])null)); //where null is the scope array,

This will, in turn call your com.facebook.FacebookOAuthService.processReceivedAuthorization when Facebook does an HTTP-Redirect. The code is then your Authorization Code received from Facebook.

Hope this helps!

PS Facebook doesn't do an HTTP-Redirect to your page when requesting access token, hence why you're manually storing it in a session and not JOAuth (It uses OAuth 2 draft 0). If other OAuth 2 service provider uses HTTP-Redirect after requesting for Access Token, don't store the Access Token, the OAuth2Service does it automatically for you.
PPS Use any logging framework to see logs.

Good luck and let me know what comes up!

Sign up to request clarification or add additional context in comments.

4 Comments

It's my pleasure :) Btw, how did you hear about JOAuth?
from you. stackoverflow.com/questions/5248484/… :) btw thank you for providing the full information so i can actually understand what i'm doing and not just to copy/paste the code.
Aaah! :) I forgot that I made a comment on that question. Have fun with JOAuth! Btw, copy/pasting of code is ok if you know what you're doing (fine-tuning). Also, keeping my name on your code seems like you're plagiarizing it....lol
hi again! still trying to properly work with your tool. please let me know if you can provide any information to enlight me regarding the following issue: stackoverflow.com/questions/5615193/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.