- 登录Facebook官网注册一个开发者账号:https://developers.facebook.com/
- 创建一个应用(APPS)
- 在自己创建的应用中可以看到自己的应用编号和应用密钥
- 在设置中可以创建一个回调,这个是回调地址,比如http://localhost:8080/facebookLogin
- 获取code值:https://www.facebook.com/dialog/oauth?client_id=应用编号&redirect_uri=回调地址&code=,这时在地址栏上会出现一长串code
- 获取access_token:https://graph.facebook.com/oauth/access_token?client_id=应用编号&redirect_uri=回调地址&client_secret=应用密钥&code=刚才获取到的code
- 获取用户资料:https://graph.facebook.com/me?access_token=刚才获取到的access_token,得到用户的id和name
- 开始eclipse开发,配置文件facebook.xml内容:
<?xml version="1.0" encoding="UTF-8"?> <config id="facebook"> <params> <param name="clientId" value="应用编号" /> <param name="secretKey" value="应用密钥" /> <param name="redirectUri" value="回调地址" /> </params> <authUrl> <![CDATA[ https://graph.facebook.com/oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUri} ]]> </authUrl> <tokenUrl> <![CDATA[ https://graph.facebook.com/oauth/access_token?client_id=${clientId}&redirect_uri=${redirectUri}&client_secret=${secretKey}&code=${code} ]]> </tokenUrl> <userInfoApi> <![CDATA[ https://graph.facebook.com/me?access_token=${accessToken} ]]> </userInfoApi> </config>
- 获取配置文件信息完成登录
代码附件:http://download.csdn.net/download/mxy_0223/9903337@Autowired private IUserService userService; @RequestMapping("/getCode") public void getUserCode(ModelAndView model,HttpServletResponse response) throws ServletException, IOException { String authUrl = OAuthHelper.getInfo("facebook").getAuthUrl(); response.sendRedirect(authUrl.trim()); } @RequestMapping("/getLogin") public void getUserLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String code = request.getParameter("code"); String tokenURL = OAuthHelper.getInfo("facebook").getTokenUrl(code).trim(); String ret =OAuthHelper.httpGet(tokenURL);//返回带token的json字符串 JSONObject obj = JSON.parseObject(ret); String access_token=(String) obj.get("access_token");//取出token String userInfoApiUrl=OAuthHelper.getInfo("facebook").getUserInfoApiUrl(access_token).trim(); String uinfoma = OAuthHelper.httpGet(userInfoApiUrl);//返回的用户信息json字符串 if(uinfoma!=null){//授权成功 JSONObject oobj = JSON.parseObject(uinfoma); String userid=(String) oobj.get("id"); String thirdId="facebook_"+userid;//第三方平台的id User persistenceUser = userService.findUserByThirdId(thirdId);//判断本地否存在 if(persistenceUser==null){//本地不存在则注册一个本地账号 User user = new User(thirdId); userService.insertUser(user); } // 用户信息存入session,跳转到用户页 toSuccessPage(request, response); } else { // 授权过程出现错误,进入错误页 toErrorPage(request, response); } }
简单的faceBook第三方登录Demo
最新推荐文章于 2024-09-03 17:44:28 发布