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
- User will click on Auth login link
- Facebook Auth server will show permission screen to user
- Once user accepts to the scope, It will send code to App Server ( Redirect URI)
- Once we got code, get access token by using client secret id
- Access User's Information using that access token
Get OAuth 2.0 Credentials from Facebook App Dashboard
- Go to Facebook Developer's Page.
- Go to Apps > Add New App
- 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
- Goto Dashboard of the above created app, There you can see your app client id and secret id.
- 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
- client_id: Which you got at Facebook developer's app dashboard
- redirect_uri: Redirect URI to which code has to be redirected
- 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
client_id= client id
&redirect_uri= redirect URI
&scope=email
&scope=user_friendsGet 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(); } } }
your demo worked fine but when i downloaded the project it is giving
ReplyDeleteUser ID 988777557906901
First Name null
Last Name null
Gender null
Link null
Name Asheesh Kumar
Use scope parameter like in facebook specified documentation https://developers.facebook.com/docs/facebook-login/permissions
DeleteThis comment has been removed by the author.
Delete<a href="https://www.facebook.com/dialog/oauth?client_id=961097254012004&redirect_uri=http://localhost:8088/FacebookAuth/oath&scope=email&scope=user_friends"
ReplyDeleteIts getting same problem while we are using different types of scop parameters.
ReplyDeletesuggest some other way
I have a similar problem, did you find a workaround on this?
DeleteI am getting SSl error: CWPKI0429I: The signer might need to be added to the local trust store.
ReplyDeletePlease provide example for java web application.
ReplyDeleteYou need to specify the fields to be displayed
ReplyDeleteExample: https://graph.facebook.com/me?fields=name,email,id&access_token=[TOKEN]
Used the exact same code here and getting the profile pic,id and name, everything else is NULL....
ReplyDeleteTried playing around with the scope but with no luck...
Any ideas?
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
ReplyDeleteVery nicely explained simple and short.
ReplyDeleteHi,
ReplyDeleteWhen 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 ?
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
ReplyDeleteRegular 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
ReplyDeleteYou are welcome to my blog: smm panel
Nice Article,
ReplyDeleteWe are the best SMM Services Provider, Increase your Social Media Account's Followers Now at cheap prices. Visit Us Now: https://www.thesmmstore.com
Hey There. I discovered your blog the use of msn. This is a really well written article.
ReplyDeleteI'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
World's cheapest SMM reseller panel
ReplyDeleteSMM (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/
Best SMM Panel (ForSMM) To Grow Social Accounts and your popularity by selling Followers, Likes, Views And More...
ReplyDeletewww.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
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.
ReplyDeleteI have to look for goals with essential information on given point and offer them to instructor our inclination and the article. ufa.
ReplyDeleteNice 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
Great article with excellent idea!Thank you for such a valuable article. I really appreciate for this great information. 바카라사이트
ReplyDeleteThis is just the information I am finding everywhere. Thanks for your blog, I just subscribe your blog. This is a nice blog..
ReplyDeleteufabet
ufa
sexy baccarat
slotxo
sagame