CS6320:  SW Engineering of Web Based Systems

 

Java Servlet and supporting class to Facebook app Authenticate from a Java EE webapp

 

 

FROM http://dyutiman.wordpress.com/2011/04/15/facebook-canvas-app-authentication-java/

This code uses Jackson to map Json to Object here. But any other API can be used too.

This mapper (or, data binder, or codec) provides functionality for converting between Java objects (instances of JDK provided core classes, beans), and matching JSON constructs. It will use instances of JsonParser and JsonGenerator for implementing actual reading/writing of JSON.

EXAMPLE Servlet using the code below that supports Authentication processing



IN doPost Method
   String signedRequest = (String) request.getParameter("signed_request"); //if authenticated this will be parameter sent to you from Facebook

//create instance of FacebookSignedRequest based on signedRequest parameter retrieved above // note even if not authenticated you still get a signedRequest but, the oauth parameter will not be set
   FacebookSignedRequest facebookSignedRequest = FacebookAuthService.getFacebookSignedRequest(signedRequest); PrintWriter writer = response.getWriter(); //if the signedRequest was null, no authentication then the called to getOauth_token() will be null // redirect to authentication URL if (facebookSignedRequest.getOauth_token() == null) {      response.setContentType("text/html");       writer.print("<script> top.location.href='" + FacebookAuthService.getAuthURL() + "'</script>");       writer.close(); } else { //we are authenticated at this point and going to forward the accessToken to your business logic Servlet/JSP      request.setAttribute("accessToken", facebookSignedRequest.getOauth_token());       RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/YOUR_NEXT_PATH"); //you will change the path to map to business logic Servlet/JSP       requestDispatcher.forward(request, response); }

 

class FacebookSignedRequest represents signed_request returned from Facebook to app

public class FacebookSignedRequest {
private String algorithm; private Long expires; private Long issued_at; private String oauth_token; private Long user_id; private FacebookSignedRequestUser user; public String getAlgorithm() { return algorithm; } public void setAlgorithm(String algorithm) { this.algorithm = algorithm; } public Long getExpires() { return expires; } public void setExpires(Long expires) { this.expires = expires; } public Long getIssued_at() { return issued_at; } public void setIssued_at(Long issued_at) { this.issued_at = issued_at; } public String getOauth_token() { return oauth_token; } public void setOauth_token(String oauth_token) { this.oauth_token = oauth_token; } public Long getUser_id() { return user_id; } public void setUser_id(Long user_id) { this.user_id = user_id; }
public FacebookSignedRequestUser getUser() { return user; }

         public void setUser(FacebookSignedRequestUser user) { this.user = user; } //inner class used to represent user information public static class FacebookSignedRequestUser {
            private String country;     private String locale;     private FacebookSignedRequestUserAge age;    public String getCountry() {       return country;    }

           public void setCountry(String country) {       this.country = country;    }

   public String getLocale() {       return locale;    }

   public void setLocale(String locale) {       this.locale = locale;    }

   public FacebookSignedRequestUserAge getAge() {       return age;    }

   public void setAge(FacebookSignedRequestUserAge age) {       this.age = age;    }


       public static class FacebookSignedRequestUserAge{      private int min;      private int max;


     public int getMin() {           return min;      }


    public void setMin(int min) {          this.min = min;     }


    public int getMax() {          return max;     }


    public void setMax(int max) {     this.max = max;     }    }    } }

Java Class FacebookAuthService to represent Call for Authentication to Facebook

public class FacebookAuthService {
         private static final String apiKey = "APP_KEY"; //you will change this private static final String appSecret = "APP_SECRET"; //you will change this private static final String appId = "APP_ID"; //you will change this private static final String redirect_uri = "https://apps.facebook.com/YOUR_APP_PATH"; //you will change this private static final String[] perms = new String[] {"publish_stream", "email"}; public static String getAPIKey() { return apiKey; } public static String getSecret() { return appSecret; } public static String getLoginRedirectURL() { return "https://graph.facebook.com/oauth/authorize?client_id=" + appId + "&display=page&redirect_uri=" + redirect_uri + "&scope=" + StringUtils.join(perms); } public static String getAuthURL(String authCode) { return "https://graph.facebook.com/oauth/access_token?client_id=" + appId + "&redirect_uri=" + redirect_uri + "&client_secret=" + appSecret + "&code=" + authCode; } public static String getAuthURL() { return "https://www.facebook.com/dialog/oauth?client_id=" + appId + "&redirect_uri=" + redirect_uri + "&scope=" + StringUtils.join(perms); } //this is the method that creates instance of FacebookSignedRequest using returned Facebook signed_request info public static FacebookSignedRequest getFacebookSignedRequest(String signedRequest) throws Exception{    //parst the json string returned from Authentication and grab the oauth token String payLoad = signedRequest.split("[.]", 2)[1];    payLoad = payLoad.replace("-", "+").replace("_", "/").trim();    String jsonString = new String(Base64.decodeBase64(payLoad)); //this maps the returned response from that has the jsonString as the signed_request returned from Facebook
//to an instance of the FacebookSignedRequest class.
// uses 3rd party package called Jackson to do mapping of JSON string to an object.    return new ObjectMapper().readValue(jsonString, FacebookSignedRequest.class); } } NOTE:
This code uses Jackson to map Json to Object here. But any other API can be used too.

This mapper (or, data binder, or codec) provides functionality for
converting between Java objects (instances of JDK provided core classes,
beans), and matching JSON constructs. It will use instances of JsonParser and JsonGenerator (classes in Jackson package)for implementing actual
reading/writing of JSON.

 

© Lynne Grewe