일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 업캐스팅
- 다운캐스팅
- 추상클래스
- 단축키
- 페이징
- 로또
- 상속예제
- Login with OAuth Authentication
- 상속
- 자바
- 자바 야구게임
- Random
- 전체텍스트
- 전자정부
- Full text
- 형변환
- while
- 전체
- 야구게임
- 가변인자
- 25가지 효율적인 sql작성법
- Validations
- 스프링
- IBatis procedure
- jquery
- angular2
- full text indexing
- 다형성
- 이클립스
Archives
- Today
- Total
nalaolla
Java Facebook Login with OAuth Authentication 본문
728x90
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 Login Page
Screen shot shown in the start of this tutorial is the login page in our application and following is the code.
<%@page import="com.javapapers.java.social.facebook.FBConnection"%> <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <% FBConnection fbConnection = new FBConnection(); %> <!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>Java Facebook Login</title> </head> <body style="text-align: center; margin: 0 auto;"> <div style="margin: 0 auto; background-image: url(./img/fbloginbckgrnd.jpg); height: 360px; width: 610px;"> <a href="<%=fbConnection.getFBAuthUrl()%>"> <img style="margin-top: 138px;" src="./img/facebookloginbutton.png" /> </a> </div> </body> </html>
Application redirect URL
Following is the page the Facebook issues a redirect request to the browser.
package com.javapapers.java.social.facebook; 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 MainMenu 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")); } }
Facebook Get Access Token
package com.javapapers.java.social.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 = "234231262685378"; public static final String FB_APP_SECRET = "y2a73dede3n49uid13502f5ab8cdt390"; public static final String REDIRECT_URI = "http://localhost:8080/Facebook_Login/fbhome"; 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; } }
Access Facebook Graph Profile Data
package com.javapapers.java.social.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 MapgetGraphData(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; } }
Facebook Authentication Success and Profile Data
중요사항..
현재 facebook은 id와 name만 기본으로 리턴해주고 있다..
다른 필드값도 가져오고 싶다면..
String g = "https://graph.facebook.com/me?" + accessToken;
위 부분을
다음과 같이 수정하면 된다..
String g = "https://graph.facebook.com/me?" + accessToken + "&fields=name,email,first_name,last_name";
토큰값 뒤에 받고자 하는 필드를 명시해줘야한다..
이 부분때문에 하루를 버렸다..젠쟝...
728x90
'SPRING' 카테고리의 다른 글
<util:properties/> 와 Spring EL 로 값 가져오기 (0) | 2016.07.04 |
---|---|
Properties 설정 및 Java, Jsp, Xml 소스에서 사용 방법 (0) | 2016.07.04 |
스프링(Spring) 개발 - (18) 페이징 (jQuery와 Ajax) (2) | 2016.06.25 |
스프링(Spring) 개발 - (17) 페이징 (전자정부 프레임워크 이용) (0) | 2016.06.25 |
스프링(Spring) 개발 - (16) AOP 설정하기 (부제: Controller에도 AOP 적용하기) (0) | 2016.06.25 |