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();
        }

    }

}

51 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
  8. I have recently started a blog, the info you provide on this site has helped me greatly. Thanks for all of your time & work free facebook video downloader

    ReplyDelete
  9. Very nicely explained simple and short.

    ReplyDelete
  10. Hi,

    When am trying to make the substring from outstring , am getting an indexoutofbound exception .... as its unable to find the & in outsting ..... can you plz help me out in this ?

    ReplyDelete
  11. I really thank you for the valuable info on this great subject and look forward to more great posts. Thanks a lot for enjoying this beauty article with me. I am appreciating it very much! Looking forward to another great article. Good luck to the author! All the best! smm panels list

    ReplyDelete
  12. Regular visits listed here are the easiest method to appreciate your energy, which is why why I am going to the website everyday, searching for new, interesting info. Many, thank you

    You are welcome to my blog: smm panel

    ReplyDelete
  13. Nice Article,
    We are the best SMM Services Provider, Increase your Social Media Account's Followers Now at cheap prices. Visit Us Now: https://www.thesmmstore.com

    ReplyDelete
  14. Hey There. I discovered your blog the use of msn. This is a really well written article.
    I'll be sure to bookmark it and return to read extra of your helpful information.
    Thank you for the post. I'll definitely comeback. my blog: international smm panel

    ReplyDelete
  15. World's cheapest SMM reseller panel
    SMM (Social Media Marketing) is the use of social media platforms such as Instagram, Facebook, Twitter, Youtube and many more to promote yourself or your company. If you are looking for a way to boost your online presence, then your best choice is to use INM (INCRESERMASTER) where we offer services to help you boost your online presence across ALL social media platforms for the cheapest prices
    https://incresermaster.com/

    ReplyDelete
  16. Best SMM Panel (ForSMM) To Grow Social Accounts and your popularity by selling Followers, Likes, Views And More...

    www.forsmm.net

    Without no doubt social media platforms have become the next best choice in
    electronic marketing after the popularity of search engines and sometimes they are arguably better than the search engines and and shortlt with an easier method. If you are an active user on social media, you can reach potential customers easily with a lower cost than search engines. Your company can grow quickly by optimizing social media accounts. You can do this easily by
    using the www.forsmm.net social media panel..

    What Is SMM Panel and How Does It Work?

    An SMM panel is a highly technical tool for providing services to social media platforms to help you grow your business or personal accounts to optimize and serve it to your clients in research to make your customers reach you more easily. Let me give you an example, you can buy,order Facebook likes to make your page better and popular in search and similarly, you can buy YouTube views,likes even shares and also many platforms like Instagram, Twitter, Twitch, etc.To make your business optimize to your customers in a more reliable and proficient way.

    You can use this Panel for many purposes.You can lead your dream business to the desired success with by only clicking the right choices in our services. It has an “easy to use” interface which will make everything easy for yourpersonal or business account growth, and ease of payment, get followers, get likes and views and many many more.This services panel will lead you to become a gold option on social media by finding right and desired customers for yoı. If you are looking to grow your social media accounts then you are in the very right place. You can make your Facebook page get thousands of likes and comments, your account on
    Instagram, you can make it get thousands of followers quickly, which will make your account reliable to customers

    What are the advantages of the panel?

    Very fast orders complete
    You can make unlimited orders(We mean Unlimited)
    You will get unlimited and reliable services
    You will find many payment methods
    Easy support for users through tickets 24/7
    Support many social media platforms
    Best cheapest Panel prices
    Best High-Quality services

    You can simply use this services panel to get likes , fans, and followers to reach and intearct with customers and gain that trust from customers. It will reduce the the time you wait for your business success, increase your experience and confidence when dealing with your customers, It will also save your time and effort.

    Choose the Best SMM Panel and the easiest and cheapest to use.

    You will achieve great success with little effort, and success
    will boost your confidence in your business and deal with your customers. You
    can do many successes in a short time and earn a lot with a few clients. You
    don’t need a team or gain experience or knowledge to handling the Panel. It is
    very easy and you will know how to make an order just by see the SMM Panel
    dashboard

    In the past few years, online commerce has increased rapidly and
    is still growing, making competition in e-marketing more difficult. Optimizing
    social media will make you lead the competition with ease. But you can take the
    lead in social media marketing with the help of this Panel
    FoxFollow Best SMM Panel and Top SMM Provider You Will get best quality with cheapest prices for all social media marketing services. Followers, Likes, Views, Comments and more High Quality Services For All Social Media Platforms. instagram, Facebook, Twitter, Youtube and Many Websites Get Followers Now.
    www.forsmm.net


    ReplyDelete
  17. Fantastic website. Lots of useful info here. I am sending to some friends ans additionally sharing in delicious. get one of the best SMM Panel Provider India then visit on our website.

    ReplyDelete
  18. I have to look for goals with essential information on given point and offer them to instructor our inclination and the article. ufa.

    Nice to be visiting your blog again, it has been months for me. Well this article that i've been waited for so long. Much obliged for sharing. ufa1688

    ReplyDelete
  19. Great article with excellent idea!Thank you for such a valuable article. I really appreciate for this great information. 바카라사이트

    ReplyDelete
  20. This is just the information I am finding everywhere. Thanks for your blog, I just subscribe your blog. This is a nice blog..

    ufabet
    ufa
    sexy baccarat
    slotxo
    sagame

    ReplyDelete
  21. What an interesting story! I'm glad I finally found what I was looking for 바둑이사이트.

    ReplyDelete
  22. As a business owner or marketing strategist, social media is an important tool to increase brand awareness, we can see social media like a cocktail party, where you can have networking and fun. I will explain 10 Must-Haves in your campaign to rock your social media strategy. check this link right here now

    ReplyDelete
  23. Watch movies online sa-movie.com, watch new movies, series Netflix HD 4K, watch free movies on your mobile phone, Tablet, watch movies on the web. ดูหนังออนไลน์


    SEE4K Watch movies, watch movies, free series, load without interruption, sharp images in HD FullHD 4k, all matters, all tastes, see anywhere, anytime, on mobile phones, tablets, computers. ดูหนังใหม่


    GangManga read manga, read manga, read manga online for free, fast loading, clear images in HD quality, all titles, anywhere, anytime, on mobile, tablet, computer. อ่านการ์ตูน


    Watch live football live24th, watch football online, link to watch live football, watch football for free. ผลบอลสดa

    ReplyDelete
  24. เราคือผู้นำด้านเกมพนันออนไลน์ Major168 เราคือผู้ให้บริการ คาสิโนออนไลน์ คาสิโนออนไลน์ ที่ได้รับรองว่าดีที่สุดในประเทศไทย มีค่ายเกมส์ให้เล่นมากมาย Sagaming, Sexy bacarat, Dreamgame, Ebet, Wm casino, Vivo gaming ไม่ผ่านเอเย่นต์ ระบบปลอดภัยมีทีมงานดูแลตลอด 24ชม.

    SAGAME88 แหล่งรวมเกมส์พนันออนไลน์ คาสิโนสด บาคาร่า กำถั่ว คาสิโนออนไลน์ ไฮโล รูเล็ต รับเครดิตฟรีเล่นได้ทุกเกมส์ โบนัสสมาชิกใหม่เพียบ พร้อมระบบฝากถอนออโต้ 10วิ เรามีทุกค่ายเกมส์ให้คุณเลือกเดิมพัน SA Game Sexy bacarat Dreamgame WM Casino VIVO Gaming Ebet เล่นได้ทุกเกมส์

    Our website ufabet provides betting services in the system of Auto Deposit-Withdrawal. Our members are not only in Thailand. Online football betting UEFA Bet market And this makes a guarantee that Ufabet168 is another reliable football betting website

    ufa through the website UFABET1688 a web gambling online , one that integrated all the bets from online casinos , online casino , online , and also have a game a lot more to be chosen to play such games.

    ReplyDelete
  25. As soon as I noticed this internet site I went on reddit to share some of the love with them. 안전놀이터

    ReplyDelete
  26. I haven't seen anything interesting in a long time, and I'm writing on this form, so I hope to see you.토토사이트

    ReplyDelete
  27. Thanks for explaining everything here in your post. We are Haldwani, Uttarakhand based real estate dealers, for any such contact us at www.99haldwaniproperties.com.

    ReplyDelete
  28. This is the best blog annualeventpost I ever see. Thanks for sharing information with us.

    ReplyDelete
  29. Nice post. I used to be checking constantly this blog and I am impressed! Extremely useful info particularly the ultimate section 🙂 I take care of such information a lot. I was seeking this certain information for a long time. Thank you and best of luck.
    the fault in our stars pdf

    ReplyDelete
  30. Are you searching for nursing assignment help? We offer you the best academic writing services including the help you need to create a nursing assignment. Visit our website for more help.

    ReplyDelete
  31. This is the perfect post.안전놀이터 It helped me a lot. If you have time, I hope you come to my site and share your opinions. Have a nice day.

    ReplyDelete
  32. ufabet168 Thanks for sharing this wonderful post with us and hoping that you will continue doing this job on the daily basis to guide us in a better way.

    ReplyDelete

  33. Thank you for sharing your info. I really appreciate your efforts and Thanks a lot for sharing a piece of wonderful information which I am looking for a longer period of time.
    Mcafee.com/activate | Mcafee.com/activate

    ReplyDelete



  34. Time saver: The online Assignment help you to save a lot of time by using it as the students have more works to do, the assignment helps to reduce their workload and saves time also the work is done effectively.


    ReplyDelete
  35. I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post. ufabet168

    ReplyDelete
  36. This is quite a good blog.Are you also searching for BSN Writing Services? we are the best solution for you. We are best known for delivering the best bsn writing services to students without having to break the bank.

    ReplyDelete

  37. Assignment help Canada services provide essays, research, papers, dissertations, thesis, lab reports, personal statements, statistics projects, programming assignments, PowerPoint presentations etc. They help you with anything and everything you need.

    ReplyDelete
  38. Usually I never comment on blogs but your article is so convincing that I never stop myself to say something about it. You’re doing a great job Man,Keep it up smm panel

    ReplyDelete
  39. Thank you so much for writing an amazing post on Google GSON Java Library, I see you have an charismatic personality and you have complete grip on every topic you write on. You are like an expert as Assignment Writing Services experts are.

    ReplyDelete

Blogroll

Follow this blog by Email

Popular Posts