Facebook is providing OAuth Service. You can implement Facebook Login on your website so that user doesn't need to remember another password for your website. You will also get worthy email addresses to connect with users. Get Google GSON Java Library to handle JSON responses.

OAuth 2.0 Flow

  1. User will click on Auth login link
  2. Facebook Auth server will show permission screen to user
  3. Once user accepts to the scope, It will send code to App Server ( Redirect URI)
  4. Once we got code, get access token by using client secret id
  5. Access User's Information using that access token 

Get OAuth 2.0  Credentials from Facebook App Dashboard

  1. Go to Facebook Developer's Page.
  2. Go to Apps > Add New App
  3. Enter Site URL and Mobile Site URL. You need to enter your Site URL here. for example "http://demo.sodhanalibrary.com/". After processing User permissions screen, facebook will redirect the code value to this URL 
  4. Goto Dashboard of the above created app, There you can see your app client id and secret id.
  5. If you want to make your app available to public, You need to enter lot of app details. Be patience and complete them.

Download Project 

Download sample project from here. Open Setup.java and give required app details. Open auth/facebook.html  modify the login URL

Form the URL

Now we need to create a button with Auth URL. Syntax of the URL is
https://www.facebook.com/dialog/oauth?[parameters]

Some important Query Paramenters

  1. client_id: Which you got at Facebook developer's app dashboard
  2. redirect_uri: Redirect URI to which code has to be redirected
  3. scope: to get profile info give profile as scope, to get email address give email as scope

The Auth URL get Users Email Address

 https://www.facebook.com/dialog/oauth?
 client_id= client id
 &redirect_uri= redirect URI
 &scope=email
 &scope=user_friends

Get Access Token 

Once user click on above link, It will ask for User's permission to provide information to your site. Once user click on accept it will redirect to Your APP Redirect URI?code=[some code here]. Here you will get code value at server side. So you need to access this from Java or PHP or any other server side language.

Get Code value and format URL

String code = request.getParameter("code");
URL url = new URL("https://graph.facebook.com/oauth/access_token?client_id="
        + clientID + "&redirect_uri=" + redirectURI
        + "&client_secret=" + clientSecret
        + "&code=" + code);

Send request for Access Token

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
String line, outputString = "";
BufferedReader reader = new BufferedReader(
        new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
    outputString += line;
}
System.out.println(outputString);
String accessToken = null;
if(outputString.indexOf("access_token")!=-1) {
    int k=outputString.length();
    accessToken = outputString.substring(k+1,outputString.indexOf("&"));
}

Get User Info

url = new URL("https://graph.facebook.com/me?access_token="+ accessToken);
System.out.println(url);
URLConnection conn1 = url.openConnection();
outputString = "";
reader = new BufferedReader(new InputStreamReader(conn1.getInputStream()));
while ((line = reader.readLine()) != null) {
    outputString += line;
}
reader.close();
System.out.println(outputString);
FaceBookPojo fbp = new Gson().fromJson(outputString, FaceBookPojo.class);

User Info in JSON Format

{
    "id":"user id here",
    "first_name":"name here",
    "last_name":"given name here", 
    "link":"family name here",
    "user_name":"your name here"  
    "email":"your email here"
}

Pojo class to handle response

public class FaceBookPojo {
    String id;
    String name;
    String first_name;
    String last_name;
    String link;
    String user_name;
    String email;
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getFirst_name() {
        return first_name;
    }
    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }
    public String getLast_name() {
        return last_name;
    }
    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }
    public String getLink() {
        return link;
    }
    public void setLink(String link) {
        this.link = link;
    }
    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;
    }
}

Whole Servlet code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import demo.factory.GlobalCons;
import demo.pojo.FaceBookPojo;

/**
 * Servlet implementation class Oauh2fb
 */
public class OAuth2fb extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    // Set Facebook App details here 
    private static final String clientID = "your app client id here";
    private static final String clientSecret = "your app secret id here";
    private static final String redirectURI = "redirect uri here";

    /**
     * @see HttpServlet#HttpServlet()
     */
    public OAuth2fb() {
        super();

    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        try {
            String rid = request.getParameter("request_ids");
            if (rid != null) {
                response.sendRedirect("https://www.facebook.com/dialog/oauth?client_id="
                        + clientID + "&redirect_uri=" + redirectURI);
            } else {
                // Get code
                String code = request.getParameter("code");
                if (code != null) {
                    
                    // Format parameters
                    URL url = new URL(
                            "https://graph.facebook.com/oauth/access_token?client_id="
                                    + clientID + "&redirect_uri=" + redirectURI
                                    + "&client_secret=" + clientSecret
                                    + "&code=" + code);
                    
                    // request for Access Token
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.setRequestMethod("GET");
                    String line, outputString = "";
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(conn.getInputStream()));
                    while ((line = reader.readLine()) != null) {
                        outputString += line;
                    }
                    System.out.println(outputString);
                    
                    // extract access token from response
                    String accessToken = null;
                    if(outputString.indexOf("access_token")!=-1) {
                        accessToken = outputString.substring(13,outputString.indexOf("&"));
                    }
                    
                    // request for user info
                    url = new URL("https://graph.facebook.com/me?access_token="
                            + accessToken);
                    System.out.println(url);
                    URLConnection conn1 = url.openConnection();
                    outputString = "";
                    reader = new BufferedReader(new InputStreamReader(
                            conn1.getInputStream()));
                    while ((line = reader.readLine()) != null) {
                        outputString += line;
                    }
                    reader.close();
                    System.out.println(outputString);
                    
                    // convert response JSON to Pojo class
                    FaceBookPojo fbp = new Gson().fromJson(outputString,
                            FaceBookPojo.class);
                    System.out.println(fbp);
                                    }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

10 comments:

  1. your demo worked fine but when i downloaded the project it is giving


    User ID 988777557906901
    First Name null
    Last Name null
    Gender null
    Link null
    Name Asheesh Kumar

    ReplyDelete
    Replies
    1. Use scope parameter like in facebook specified documentation https://developers.facebook.com/docs/facebook-login/permissions

      Delete
    2. This comment has been removed by the author.

      Delete
  2. <a href="https://www.facebook.com/dialog/oauth?client_id=961097254012004&redirect_uri=http://localhost:8088/FacebookAuth/oath&scope=email&scope=user_friends"

    ReplyDelete
  3. Its getting same problem while we are using different types of scop parameters.

    suggest some other way

    ReplyDelete
    Replies
    1. I have a similar problem, did you find a workaround on this?

      Delete
  4. I am getting SSl error: CWPKI0429I: The signer might need to be added to the local trust store.

    ReplyDelete
  5. Please provide example for java web application.

    ReplyDelete
  6. You need to specify the fields to be displayed
    Example: https://graph.facebook.com/me?fields=name,email,id&access_token=[TOKEN]

    ReplyDelete
  7. Used the exact same code here and getting the profile pic,id and name, everything else is NULL....
    Tried playing around with the scope but with no luck...
    Any ideas?

    ReplyDelete

Blogroll

Follow this blog by Email

Popular Posts