Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 

This blog is part of 1 Tute Sets.

restfb
  • Facebook OAuth Authentication using Java

    • 1/1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 3.74k
    Comment on it

    Hi,

    This blog is to help you to get Facebook Authentication through OAuth using Java. As Facebook is not offering any SDK for Java clients so with the use of a Json parser we are going to develop a small web application in order to use Facebook Authentication. You can download java Json jar from here http://www.java2s.com/Code/Jar/j/Downloadjavajsonjar.htm

    First of all you need get registered with Facebook and need to Sign in into developer account.

    After Sign In into Facebook Developer Account.

    • Go to my apps
    • Click Add a New App

     

    • Select website from there.
    • You have to give a name for your new app or you can choose from pre existing ones.
    • After giving a new name you have to click on create new Facebook app id.
    • Then you will be prompted to provide some necessary details.
    • Click on create app id.

    you can skip the get started tutorial.

    Now you will get dashboard page of your app. In which App Id and app secrete will be given which will be used by your application.

     

    You can assign different user roles to different users by selecting the option role in context with your app. Here you can add or assign users in different roles to be used until your app is in development phase. You can also add multiple test user for you app as Facebook provides this feature to create multiple test users.

    • Go to the setting section of it.

     

    • Put your app domain there for example localhost or you can also put multiple domains there and then click on add platform. Select website from there. Here you have to provide the URL of your app where you need to be redirected after Facebook authentication eg: http://localhost:8080/myapp/fbhome
    • Click on save changes.

    Create an Dynamic Web Project in eclipse.

    • Give name to your new Web Application as myapp.
    • Now create a Facebook login page for that.
    • Put the downloaded java-json.jar to lib directory.

    For that I created a index.jsp under WebContent folder an add the following code to it. 

    <%@ page language="java" contentType="text/html; charset=UTF-8"
    	pageEncoding="UTF-8"%>
    <%@ page import="com.tech.facebook.CreateFBConnection"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Test Facebook OAuth</title>
    </head>
    <body>
    	<%
    		CreateFBConnection fbConnection = new CreateFBConnection();
    	%>
    	<h3>Test Facebook Authentication</h3>
    	<a href="<%=fbConnection.getFBAuthUrl()%>">Facebook Login</a>
    </body>
    </html>
    

    Now we need to add some classes in our application in order to use Facebook Authentication.

    Create a package under src folder say com.tech.facebook

     

    Create a CreateFBConnection class in it.

    package com.tech.facebook;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;
    import java.net.URLEncoder;
    
    public class CreateFBConnection {
    	public static final String APP_ID = "685668414904304";
    	public static final String APP_SECRET = "754472bfb4cbef35d06094564d89e6dc";
    	public static final String REDIRECT_URI = "http://localhost:8080/myapp/fbhome";
    
    	String accessToken = "";
    
    	public String getFBAuthUrl() {
    		String fbLoginUrl = "";
    		try {
    			fbLoginUrl = "http://www.facebook.com/dialog/oauth?"
    					+ "client_id="
    					+ CreateFBConnection.APP_ID
    					+ "&redirect_uri="
    					+ URLEncoder.encode(CreateFBConnection.REDIRECT_URI,
    							"UTF-8") + "&scope=email";
    		} catch (UnsupportedEncodingException e) {
    			e.printStackTrace();
    		}
    		return fbLoginUrl;
    	}
    
    	public String getFBGraphUrl(String code) {
    		String fbGraphUrl = "";
    		try {
    			fbGraphUrl = "https://graph.facebook.com/oauth/access_token?"
    					+ "client_id="
    					+ CreateFBConnection.APP_ID
    					+ "&redirect_uri="
    					+ URLEncoder.encode(CreateFBConnection.REDIRECT_URI,
    							"UTF-8") + "&client_secret=" + APP_SECRET
    					+ "&code=" + code;
    		} catch (UnsupportedEncodingException e) {
    			e.printStackTrace();
    		}
    		return fbGraphUrl;
    	}
    
    	public String getAccessToken(String code) {
    		URL fbGraphURL;
    		try {
    			fbGraphURL = new URL(getFBGraphUrl(code));
    		} catch (MalformedURLException e) {
    			throw new RuntimeException("Invalid code received " + e);
    		}
    		URLConnection fbConnection;
    		StringBuffer b = null;
    		try {
    			fbConnection = fbGraphURL.openConnection();
    			BufferedReader in;
    			in = new BufferedReader(new InputStreamReader(
    					fbConnection.getInputStream()));
    			String inputLine;
    			b = new StringBuffer();
    			while ((inputLine = in.readLine()) != null)
    				b.append(inputLine);
    			in.close();
    		} catch (IOException e) {
    			throw new RuntimeException("Unable to connect with Facebook " + e);
    		}
    		accessToken = b.toString();
    		if (accessToken.startsWith("{")) {
    			throw new RuntimeException("ERROR: Access Token Invalid: "
    					+ accessToken);
    		}
    		return accessToken;
    	}
    }

     

    Create a FBGraphUtil class in the same package

    package com.tech.facebook;
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.HashMap;
    import java.util.Map;
    
    import org.json.JSONException;
    import org.json.JSONObject;
    
    public class FBGraphUtil {
    	private String accessToken;
    
    	public FBGraphUtil(String accessToken) {
    		this.accessToken = accessToken;
    	}
    
    	public String getFBGraph() {
    		String graph = null;
    		try {
    
    			String g = "https://graph.facebook.com/me?" + accessToken
    					+ "&fields=name,email,gender";
    			URL u = new URL(g);
    			URLConnection c = u.openConnection();
    			BufferedReader in = new BufferedReader(new InputStreamReader(
    					c.getInputStream()));
    			String inputLine;
    			StringBuffer b = new StringBuffer();
    			while ((inputLine = in.readLine()) != null)
    				b.append(inputLine + "\n");
    			in.close();
    			graph = b.toString();
                //System.out.println(graph);
    		} catch (Exception e) {
    			throw new RuntimeException("ERROR in getting FB graph data. " + e);
    		}
    		return graph;
    	}
    
    	@SuppressWarnings({ "unchecked", "rawtypes" })
    	public Map getGraphData(String fbGraph) {
    		Map fbUser = new HashMap();
    		try {
    			JSONObject data = new JSONObject(fbGraph);
    			fbUser.put("id", data.getString("id"));
    			fbUser.put("name", data.getString("name"));
    			if (data.has("email"))
    				fbUser.put("email", data.getString("email"));
    			if (data.has("gender"))
    				fbUser.put("gender", data.getString("gender"));
    		} catch (JSONException e) {
    			throw new RuntimeException("ERROR in parsing FB graph data. " + e);
    		}
    		return fbUser;
    	}
    }


    Create a Servlet under the same package as MyApp and add the following code to it.

    package com.tech.facebook;
    
    import java.io.IOException;
    import java.util.Map;
    
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class MyApp extends HttpServlet {
    
    	private static final long serialVersionUID = 1L;
    	private String code = "";
    
    	public void service(HttpServletRequest req, HttpServletResponse res)
    			throws ServletException, IOException {
    		code = req.getParameter("code");
    		if (code == null || code.equals("")) {
    			throw new RuntimeException(
    					"ERROR: Didn't get code parameter in callback.");
    		}
    		CreateFBConnection fbConnection = new CreateFBConnection();
    		String accessToken = fbConnection.getAccessToken(code);
    
    		res.setContentType("text/html");
    		FBGraphUtil fbGraph = new FBGraphUtil(accessToken);
    		String graph = fbGraph.getFBGraph();
            @SuppressWarnings("unchecked")
    		Map<String, String> fbProfileData = fbGraph.getGraphData(graph);
    		ServletOutputStream out = res.getOutputStream();
    		out.println("<h2>Facebook OAuth Login</h2>");
    		out.println("<div style='float:left'>");
    		out.println("<img src='https://graph.facebook.com/"
    				+ fbProfileData.get("id")
    				+ "/picture?type=square' style='border-radius:50%'alt='Profile Pic'>");
    		out.println("</div>");
    		out.println("<div style='float:left'>");
    		out.println("Name   : " + fbProfileData.get("name") + "<br>");
    		out.println("Email  : " + fbProfileData.get("email") + "<br>");
    		out.println("Gender : " + fbProfileData.get("gender") + "<br>");
    		out.println("</div>");
    	}
    
    }

     

    Update your web.xml file as given below

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app id="WebApp_ID" version="2.4"
    	xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    	<display-name>myapp</display-name>
    	<welcome-file-list>
    		<welcome-file>index.jsp</welcome-file>
    	</welcome-file-list>
    	<servlet>
    		<servlet-name>MyApp</servlet-name>
    		<servlet-class>com.tech.facebook.MyApp</servlet-class>
    	</servlet>
    
    	<servlet-mapping>
    		<servlet-name>MyApp</servlet-name>
    		<url-pattern>/fbhome</url-pattern>
    	</servlet-mapping>
    </web-app>

     

    Now run your Web application on a server.

     

    After clicking on Facebook Login hyperlink you will be redirected to Facebook login page.

    The user need to provide their login details there. After that user need to hit Okay in order to allow the app to use Facebook details permissions.

     

     

    Now we have Facebook returned User details with us.
    For more information how to use Graph API explorer tool, please follow this link. http://findnerd.com/list/view/Facebook-Graph-API-explorer-Tool/19289/

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: