Press enter to see results or esc to cancel.


JAVA – Integrate Login with Facebook using graph API


In this video I have shown how you can generate Access token dynamically. And use the dynamic access to get facebook user info using facebook graph API.

Here is the steps what you have to follow.
1. Login to facebook developers site and get an APP id by creating a facebook APP.

2. Grant permission for your Domain to access the Facebook app. You can go to this link Grant Permission for the steps.
3. Project Structure in Eclipse IDE


4.Update the APP ID in the page index.jsp
index.jsp

<!DOCTYPE html>
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">
</head>
<body>
<script>
 // This is called with the results from from FB.getLoginStatus().
 function statusChangeCallback(response) {
 console.log('statusChangeCallback');
 console.log(response);
 console.log(response.authResponse.accessToken);
 //alert(response.authResponse.accessToken);
 if (response.status === 'connected') {
 window.location.href='Sign_in_Controller.jsp?access_token='+response.authResponse.accessToken; 
 } else {
 // The person is not logged into your app or we are unable to tell.
 document.getElementById('status').innerHTML = 'Please log ' +
 'into this app.';
 }
 }
 // This function is called when someone finishes with the Login
 // Button. See the onlogin handler attached to it in the sample
 // code below.
 function checkLoginState() {
 FB.getLoginStatus(function(response) {
 statusChangeCallback(response);
 });
 }
 window.fbAsyncInit = function() {
 FB.init({
 appId : 'FILL THE APP ID',
 cookie : true, // enable cookies to allow the server to access 
 // the session
 xfbml : true, // parse social plugins on this page
 version : 'v2.8' // use graph api version 2.8
 });
 FB.getLoginStatus(function(response) {
 statusChangeCallback(response);
 });
 };
 // Load the SDK asynchronously
 (function(d, s, id) {
 var js, fjs = d.getElementsByTagName(s)[0];
 if (d.getElementById(id)) return;
 js = d.createElement(s); js.id = id;
 js.src = "https://connect.facebook.net/en_US/sdk.js";
 fjs.parentNode.insertBefore(js, fjs);
 }(document, 'script', 'facebook-jssdk'));
 // Here we run a very simple test of the Graph API after login is
 // successful. See statusChangeCallback() for when this call is made.
</script>
<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>
<div id="status">
</div>
</body>
</html>

5. Sign_in_Controller.jsp


<%@page import="com.chillyfacts.com.profile.Profile_Bean"%>
<%@page import="com.chillyfacts.com.profile.Profile_Modal"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String access_token=(String)request.getParameter("access_token");
Profile_Modal obj_Profile_Modal=new Profile_Modal();
Profile_Bean obj_Profile_Bean= obj_Profile_Modal.call_me(access_token);
%>
Name : <%=obj_Profile_Bean.getUser_name() %><br>
Email : <%=obj_Profile_Bean.getEmail() %><br>
id : <%=obj_Profile_Bean.getId() %><br>
Profile Picture : <%=obj_Profile_Bean.getProfile_picture() %><br>
<img src="<%=obj_Profile_Bean.getProfile_picture() %>"></img>
</body>
</html>

6. Profile_Bean.java


package com.chillyfacts.com.profile;
public class Profile_Bean {
	private String user_name;
	private String email;
	private String profile_picture;
	private String id;
	public String getUser_name() {
		return user_name;
	}
	public void setUser_name(String user_name) {
		this.user_name = user_name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getProfile_picture() {
		return profile_picture;
	}
	public void setProfile_picture(String profile_picture) {
		this.profile_picture = profile_picture;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}	
}

7.Profile_Modal.java


package com.chillyfacts.com.profile;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
public class Profile_Modal {
	public Profile_Bean call_me(String access_token) throws Exception {
	     String url = "https://graph.facebook.com/v2.12/me?fields=id,name,picture,email&access_token="+access_token;
	     URL obj = new URL(url);
	     HttpURLConnection con = (HttpURLConnection) obj.openConnection();
	     // optional default is GET
	     con.setRequestMethod("GET");
	     //add request header
	     con.setRequestProperty("User-Agent", "Mozilla/5.0");
	     int responseCode = con.getResponseCode();
	     System.out.println("\nSending 'GET' request to URL : " + url);
	     System.out.println("Response Code : " + responseCode);
	     BufferedReader in = new BufferedReader(
	             new InputStreamReader(con.getInputStream()));
	     String inputLine;
	     StringBuffer response = new StringBuffer();
	     while ((inputLine = in.readLine()) != null) {
	     	response.append(inputLine);
	     }
	     in.close();
	     System.out.println(response);
	     Profile_Bean obj_Profile_Bean=new Profile_Bean();
	     JSONObject myResponse = new JSONObject(response.toString());
	     obj_Profile_Bean.setUser_name(myResponse.getString("name"));
	     obj_Profile_Bean.setId(myResponse.getString("id"));
	     obj_Profile_Bean.setEmail(myResponse.getString("email"));
	     JSONObject picture_reponse=myResponse.getJSONObject("picture");
	     JSONObject data_response=picture_reponse.getJSONObject("data");
	     System.out.println("URL : "+data_response.getString("url"));
	     obj_Profile_Bean.setProfile_picture(data_response.getString("url"));
		return obj_Profile_Bean;
	   }
}

8. Run the project in tomcat server. There will be login button visible.
http://localhost:8080/Facebook_Login/index.jsp

9. Login to Facebook on the Login pup up.Once you click the login button, It will ask for user permission.
App permission.

10. After successful login, It will redirect to Sign_in_Controller.jsp with active access token in the URL.
Using the active access token Restfb API will get the user information from the logged in Profile and print the name.

11. Download the complete project here.

FB_LOGIN_PROJECT.zip