JSP中的Facebook Connect示例(tomcat)

时间:2011-03-03 18:33:20

标签: java tomcat facebook oauth

我正在构建一个JSP应用程序,我想使用Facebook Connect作为用户注册和身份验证的一条路径,但我找不到有关如何获取和解析FB cookie甚至正确流程的更多信息。我正在尝试将官方documentation中找到的信息与this one之类的分步指南合并,但是用于Java。我不反对依赖像Social Java这样的库,但理解这些步骤会有所帮助。以下是我试图满足的3个用例。

  1. 我网站上未经身份验证/未注册的用户点击“Facebook Connect”按钮进行注册(捕获电子邮件,姓名和个人资料ID)并登录。
  2. 未经身份验证的用户点击“”Facebook Connect“按钮在我的域上创建有效会话。
  3. 没有连接Facebook个人资料的经过身份验证和注册的用户点击“Facebook Connect”并将Facebook个人资料ID(以及更新其电子邮件和姓名的选项)与其现有个人资料相关联。
  4. 对于这个项目,我有一个看起来像这样的Profile类(我正在使用Hibernate的优秀Project Lombok

    @Entity
    @Data
    public class Profile implements java.io.Serializable {
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      private long id;
    
      private String username;
      private String password;
      private String displayName;
      private String email;
      private String zipCode;
      private String mobileNumber;
      private String facebookId;
    
      @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
      private DateTime dateCreated;
    
      private int status;
      private int level;
    }
    

    状态和级别确实应该是枚举,但我正在努力保持这个问题的代码很小。

    免责声明:我一直在阅读很多关于如何设置Facebook Connect以进行用户注册和身份验证的博客,但它们大部分基于PHP和旧版本的Facebook API(甚至一些SO问题指向旧wiki的接受答案)。这似乎是SO社区的完美应用。

3 个答案:

答案 0 :(得分:17)

这是我使用的servlet解决方案。通过很少的调整,您可以使用简单的用户名 - 密码形式在任何JSP中使用它。不需要JavaScript! 就地址和电话号码而言,请阅读: http://developers.facebook.com/blog/post/447

FBAuthServlet

public class FBAuthServlet extends HttpServlet {

private static final Logger log = Logger.getLogger(FBAuthServlet.class);

private static final long serialVersionUID = 1L;

private UserService userService = //here goes your user service implementation

public FBAuthServlet() {
    super();
}

public void destroy() {
    super.destroy(); // Just puts "destroy" string in log
    // Put your code here
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    if ("y".equals(request.getParameter("FacebookLogin"))) {
        response.sendRedirect(FaceBookConfig.getLoginRedirectURL());
        return;
    }
    String code = req.getParameter("code");
    if (StringUtil.isNotBlankStr(code)) {
        String authURL = FaceBookConfig.getAuthURL(code);
        URL url = new URL(authURL);
        try {
            String result = readURL(url);
            String accessToken = null;
            Integer expires = null;
            String[] pairs = result.split("&");
            for (String pair : pairs) {
                String[] kv = pair.split("=");
                if (kv.length != 2) {
                    res.sendRedirect(FaceBookConfig.MAINURL);
                } else {
                    if (kv[0].equals("access_token")) {
                        accessToken = kv[1];
                    }
                    if (kv[0].equals("expires")) {
                        expires = Integer.valueOf(kv[1]);
                    }
                }
            }

            if (accessToken != null && expires != null) {

                User user = authFacebookLogin(accessToken, request.getRemoteAddr());
                if (user != null && user.getFacebookId() != null) {
                    //forward to spring security filter chain
                    res.sendRedirect(FaceBookConfig.MAINURL + "/j_spring_security_check?j_username=" + user.getEmail() + "&FaceBookId=" + user.getFacebookId());
                } else if (user != null && StringUtil.isNullOrBlank(user.getFacebookId())) {
                    res.sendRedirect(FaceBookConfig.MAINURL + "/login.html?login_error=You are not Registered By Facebook Connect");

                } else {
                    res.sendRedirect(FaceBookConfig.MAINURL);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            res.sendRedirect(FaceBookConfig.MAINURL);
        }
    }

}

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    doGet(request, response);
}

public void init() throws ServletException {
}

private String readURL(URL url) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    InputStream is = url.openStream();
    int r;
    while ((r = is.read()) != -1) {
        baos.write(r);
    }
    return new String(baos.toByteArray());
}


private User authFacebookLogin(String accessToken, String ip) {
    try {
        String content = IOUtil.urlToString(new URL("https://graph.facebook.com/me?access_token=" + accessToken));

        JSONObject resp = new JSONObject(content);
        String facebookid = resp.getString("id");
        String firstName = resp.getString("first_name");
        String lastName = resp.getString("last_name");
        String email = resp.getString("email");

        log.info("Facebook response: " + content);

        CreateUserRequestCommand comm = new CreateUserRequestCommand();

        comm.setEmail(email);
        comm.setFacebookId(facebookid);
        comm.setFirst(StringAndDateUtils.safeChar(firstName));
        comm.setLast(StringAndDateUtils.safeChar(lastName));
        //if success login
        if (userService.getUserByEmail(email) == null) {
            //if first time login
            User u = userService.createUser(comm, ip);
            return u;
        } else {//if existed
            User existedUser = userService.getUserByEmail(email);
            return existedUser;

        }
    } catch (Throwable ex) {
        ex.printStackTrace();
    }

    return null;
}
}

FBEnableServlet

public class FBEnableServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

private UserService userService = (UserService) ServiceLocator.getContext().getBean("userService");

public FBEnableServlet() {
    super();
}

public void destroy() {
    super.destroy(); // Just puts "destroy" string in log
    // Put your code here
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    if ("y".equals(request.getParameter("EnableFacebookConnect"))) {
        response.sendRedirect(FaceBookConfig.getEnableRedirectURL());
        return;
    }
    String code = req.getParameter("code");
    if (StringUtil.isNotBlankStr(code)) {
        String authURL = FaceBookConfig.getEnableAuthURL(code);
        URL url = new URL(authURL);
        try {
            String result = readURL(url);
            String accessToken = null;
            Integer expires = null;
            String[] pairs = result.split("&");
            for (String pair : pairs) {
                String[] kv = pair.split("=");
                if (kv.length != 2) {
                    res.sendRedirect(FaceBookConfig.MAINURL);
                } else {
                    if (kv[0].equals("access_token")) {
                        accessToken = kv[1];
                    }
                    if (kv[0].equals("expires")) {
                        expires = Integer.valueOf(kv[1]);
                    }
                }
            }

            if (accessToken != null && expires != null) {
                User user = authFacebookLogin(accessToken, request.getRemoteAddr());
                String loginedEmail = "";
                try {
                    loginedEmail = SecurityContextHolder.getContext().getAuthentication().getName();
                } catch (Exception ex) {

                }
                System.out.println("Logined email = " + loginedEmail);
                System.out.println("Facebook Login email = " + user.getEmail());
                if (user != null && user.getFacebookId() != null && user.getEmail().equals(loginedEmail)) {
                    userService.setFaceBookid(user.getFacebookId());
                    //forward to spring security filter chain
                    res.sendRedirect(FaceBookConfig.MAINURL + "/j_spring_security_check?j_username=" + user.getEmail() + "&FaceBookId=" + user.getFacebookId());
                } else {
                    res.sendRedirect(FaceBookConfig.MAINURL + "/secure/myAccount.html?message=Please login Facebook with same Email,you Login with " + user.getEmail());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            res.sendRedirect(FaceBookConfig.MAINURL);
        }
    }

}

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    doGet(request, response);
}

public void init() throws ServletException {
}

private String readURL(URL url) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    InputStream is = url.openStream();
    int r;
    while ((r = is.read()) != -1) {
        baos.write(r);
    }
    return new String(baos.toByteArray());
}


private User authFacebookLogin(String accessToken, String ip) {
    try {
        String content = IOUtil.urlToString(new URL("https://graph.facebook.com/me?access_token=" + accessToken));

        JSONObject resp = new JSONObject(content);
        String facebookid = resp.getString("id");
        String email = resp.getString("email");

        User existedUser = userService.getUserByEmail(email);
        if (existedUser == null) {
            return null;
        } else {
            existedUser.setFacebookId(facebookid);
            return existedUser;
        }


    } catch (Throwable ex) {
        ex.printStackTrace();
    }

    return null;
}
}

答案 1 :(得分:4)

我自己没有使用它,但Google Code上似乎有一个(非正式的)Java API:http://code.google.com/p/facebook-java-api/

答案 2 :(得分:1)

自己进行集成不需要很长时间,只需要OAuth 2.0,然后是一些用户详细信息的http请求(json格式化)。

我们在github中有一些代码(这与我们的社交模型非常相关),它检查OAuth令牌并返回用户ID(帖子底部的链接)。您可以从Facebook Connect JavaScript写入的cookie中获取当前用户的访问令牌(cookie名称以'fbs _'开头)。

https://github.com/mbst/common-social/blob/master/src/main/java/com/metabroadcast/common/social/auth/facebook/FacebookAccessTokenChecker.java