Facebook Login Integration
In the good old days users logged in by using the combination of username and password. Although nowadays some people still prefer the traditional way, a growing number of users want to sign in by using their social media accounts. But it’s getting rare and even a bit annoying when a service rolls up its own authentication mechanism instead of relying on a OAuth sign-on with our social networks. Login via social networks means fewer passwords to remember, and stronger guarantees in terms of security because you can check and control the Authorizations of the applications you use.
To Integrate Facebook Login in your application First You need to to create a web application in Facebook. After logging in to https://developers.facebook.com/ under Apps menu click “Create a New App”
Facebook Application Settings
We need to specify the application callback url in the FB settings. This will be used by the FB server on authentication to hand back control to our application.
Facebook will never call the application URL directly. A request will be sent back as response to the client browser with the callback url. The browser does the request.
Facebook OAuth Authentication Sequence Flow:
- On access of an url or in welcome page the Facebook Login button is shown. The user will click the FB button to login into the Java web application. On click of that button a Facebook URL will be invoked.
- Facebook will validate the application ID and then will redirect to its login page.
- User will enter the FB login credentials and submit the form.
- Facebook will validate the credentials and then redirect back to the browser with a request to forward to the redirect_url. Redirect_url is the URL in our application which will take care of further processing.
- Browser will call the redirect url.
- Redirect URL page will again call the Facebook to request for access_token.
- Facebook on validation success will respond back with access_token.
- Redirect URL page will again call the Facebook to request for user data by sending the access_token.
- Facebook on validating the access_token will respond back with user data requested.
- Redirect URL page will forward to a page showing user data in the client browser.
Facebook Get Access Token:
package com.uma.toDoApp.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 FBConnection {
public static final String FB_APP_ID = "455615694791777";
public static final String FB_APP_SECRET = "a5a40defe3n41uig19802f5ab8cdt250";
public static final String REDIRECT_URI = "http://localhost:8080/toDoApp/postFacebookLogin";
static String accessToken = "";
public String getFBAuthUrl() {
String fbLoginUrl = "";
try {
fbLoginUrl = "http://www.facebook.com/dialog/oauth?" + "client_id="
+ FBConnection.FB_APP_ID + "&redirect_uri="
+ URLEncoder.encode(FBConnection.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=" + FBConnection.FB_APP_ID + "&redirect_uri="
+ URLEncoder.encode(FBConnection.REDIRECT_URI, "UTF-8")
+ "&client_secret=" + FB_APP_SECRET + "&code=" + code;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return fbGraphUrl;
}
public String getAccessToken(String code) {
if ("".equals(accessToken)) {
URL fbGraphURL;
try {
fbGraphURL = new URL(getFBGraphUrl(code));
} catch (MalformedURLException e) {
e.printStackTrace();
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 + "\n");
in.close();
} catch (IOException e) {
e.printStackTrace();
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;
}
}
Get Facebook Graph Profile:
package com.uma.toDoApp.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 FBGraph {
private String accessToken;
public FBGraph(String accessToken) {
this.accessToken = accessToken;
}
public String getFBGraph() {
String graph = null;
try {
String g = "https://graph.facebook.com/me?" + accessToken;
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) {
e.printStackTrace();
throw new RuntimeException("ERROR in getting FB graph data. " + e);
}
return graph;
}
public Map getGraphData(String fbGraph) {
Map fbProfile = new HashMap();
try {
JSONObject json = new JSONObject(fbGraph);
fbProfile.put("id", json.getString("id"));
fbProfile.put("first_name", json.getString("first_name"));
if (json.has("email"))
fbProfile.put("email", json.getString("email"));
if (json.has("gender"))
fbProfile.put("gender", json.getString("gender"));
} catch (JSONException e) {
e.printStackTrace();
throw new RuntimeException("ERROR in parsing FB graph data. " + e);
}
return fbProfile;
}
}
Application Redirect URI:
package com.uma.toDoApp.facebookController;
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 FacebookController 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.");
}
FBConnection fbConnection = new FBConnection();
String accessToken = fbConnection.getAccessToken(code);
FBGraph fbGraph = new FBGraph(accessToken);
String graph = fbGraph.getFBGraph();
Map<String, String> fbProfileData = fbGraph.getGraphData(graph);
ServletOutputStream out = res.getOutputStream();
out.println("<h1>Facebook Login using Java</h1>");
out.println("<h2>Application Main Menu</h2>");
out.println("<div>Welcome "+fbProfileData.get("first_name"));
out.println("<div>Your Email: "+fbProfileData.get("email"));
out.println("<div>You are "+fbProfileData.get("gender"));
}
}
Comments
Post a Comment