spring social
2014. 2. 12. 16:04
반응형
spring social facebook
-로그인/개인프로필/친구정보 불러오기 테스트.
스프링 소셜 라이브러리를 사용하기 위해 먼저 maven 프로젝트를 생성.
그 전에 facebook 개발자센터에서 appId, secretKey를 발급 받고, 테스트할 URL을 등록이 필요하다.
-pom.xml
-propertyorg.springframework.social spring-social-core 1.0.2.RELEASE org.springframework.social spring-social-web 1.0.2.RELEASE org.springframework.social spring-social-facebook 1.0.2.RELEASE org.springframework.social spring-social-facebook-web 1.0.2.RELEASE
#facebook appId, secretKey
facebook.appId=575657749192479
facebook.secretKey=df3ebe71b7eee8771c6fee1e0124f9ec
callback.host=http://localhost:8080
-SocialController.java
-callback.jsp
@Controller
@RequestMapping("/facebook")
@PropertySource("classpath:/setting.properties")
public class SocialController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
@Resource
private Environment environment;
/**
* index
* 메인
* @param model
* @param param
* @return
*/
@RequestMapping(value = "/index", method = RequestMethod.POST)
public String index(HttpSession session, Model model){
//facebook info setting
Facebook facebook = new FacebookTemplate((String)session.getAttribute("ACCESS_TOKEN"));
FacebookProfile profile = facebook.userOperations().getUserProfile();
//List friends = facebook.friendOperations().getFriendIds();
//byte[] profiles = facebook.userOperations().getUserProfileImage();
String myId = profile.getId();
String myName = profile.getName();
String myEmail = profile.getEmail();
String myGender = profile.getGender();
Map profileInfo = new HashMap();
profileInfo.put("myId", myId);
profileInfo.put("myName", myName);
profileInfo.put("myEmail", myEmail);
profileInfo.put("myGender", myGender);
logger.info("myId=>{}", myId);
model.addAttribute("profileInfo", profileInfo);
return "index";
}
/**
* freiend Info search
* @param session
* @param model
* @return
*/
@RequestMapping(value="/getFriendInfo")
public String getFriendsInfo(HttpSession session, Model model){
Facebook facebook = new FacebookTemplate((String)session.getAttribute("ACCESS_TOKEN"));
List friends = facebook.friendOperations().getFriendIds();
model.addAttribute("friendsList", friends);
return "index";
}
/**
* facebookSignin
* 페이스북 로그인 팝업 호출
* @param response
* @param request
* @param model
* @return
* @scope user_about_me:사용자 본인 정보, publish_stream: 기본적인 쓰기권한, read_friendlists: 친구 목록
* @throws Exception
*/
@RequestMapping(value="/facebookSignIn" , method = RequestMethod.GET)
public String facebookSignin(HttpServletResponse response, HttpServletRequest request, Model model) throws Exception {
logger.info("{}","facebookSignIn START");
String callbackUrl = environment.getProperty("callback.host")+"/social/facebook/facebookAccessToken";
String oauthUrl = "https://www.facebook.com/dialog/oauth?" +
"client_id="+ environment.getProperty("facebook.appId")+"&redirect_uri="+URLEncoder.encode(callbackUrl, "UTF-8")+
"&scope=user_about_me,publish_stream,read_friendlists,offline_access";
model.addAttribute("oauthUrl", oauthUrl);
return "home";
}
/**
* facebookAccessToken
* 페이스북 로그인 결과 리턴
* @param request
* @param model
* @param message
* @param response
* @return
* @throws Exception
*/
@SuppressWarnings("deprecation")
@RequestMapping(value="/facebookAccessToken")
public String getFacebookClientAccessToken(HttpServletRequest request, Model model, @RequestParam(value="message", defaultValue="" , required=false) String message, HttpServletResponse response) throws Exception {
String code = request.getParameter("code");
String errorReason = request.getParameter("error_reason");
String errorDescription = request.getParameter("error_description");
if(logger.isInfoEnabled()){
logger.info("code => " +code);
logger.info("errorReason code => " + errorReason);
logger.info("errorDescription => " + errorDescription);
}
//facebook accessToken call
requestAccesToken(request, code);
return "callback";
}
/**
* facebook accessToken request
* 토큰값 받아옴
* @param request
* @param code
* @throws Exception
*/
public void requestAccesToken(HttpServletRequest request, String code) throws Exception{
String accessToken = "";
String result = "";
String callbackUrl = environment.getProperty("callback.host")+"/social/facebook/facebookAccessToken";
String url = "https://graph.facebook.com/oauth/access_token"+
"?client_id="+environment.getProperty("facebook.appId")+
"&client_secret="+environment.getProperty("facebook.secretKey")+
"&redirect_uri="+URLEncoder.encode(callbackUrl, "UTF-8")+
"&code="+code;
//httpGet 통신
HttpGet httpGet = new HttpGet(url);
DefaultHttpClient httpClient = new DefaultHttpClient();
result = httpClient.execute(httpGet, new BasicResponseHandler());
accessToken = result.split("&")[0].replaceFirst("access_token=", "");
//토큰값 세션처리
setAccessToken(request, accessToken);
}
/**
* setAccessToken
* 토큰값 세션 저장
* @param request
* @param accessToken
* @throws Exception
*/
public void setAccessToken(HttpServletRequest request, String accessToken) throws Exception {
request.getSession().setAttribute("ACCESS_TOKEN", accessToken);
logger.info("ACCESS_TOKEN => " + request.getSession().getAttribute("ACCESS_TOKEN"));
}
}
-home.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
facebook 로그인 하기 Sample
Spring Social Facebook oAuth
|
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
facebook 로그인 하기 Sample
-index.jsp
본인정보 |
| <이미지 태그="https://graph.facebook.com/${pInfo.myId}/picture"> |
|
myEmail: ${pInfo.myEmail} myGender: ${pInfo.myGender} myName: ${pInfo.myName} myId: ${pInfo.myId} |
친구정보 불러오기 |
| <앵커 태그="${pageContext.request.contextPath}/facebook/getFriendInfo">조회 |
|
|
반응형
'Programming > Spring' 카테고리의 다른 글
| spring mvc @ResponseBody, @RequestBody json + ajax (2) | 2014.03.12 |
|---|---|
| [Spring] Spring AOP를 이용한 메서드 추적 (0) | 2014.02.13 |
| spring mvc 모델 생성 (0) | 2014.02.11 |
| [Spring] Environment와 @PropertySource (0) | 2014.02.05 |
| 뷰 이름 명시적 지정 :ModelAndView와 String 리턴 타입 (1) | 2014.02.04 |
