JSP 中的 Facebook Connect 示例(tomcat) [英] Facebook Connect example in JSP (tomcat)

查看:14
本文介绍了JSP 中的 Facebook Connect 示例(tomcat)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个 JSP 应用程序,我想使用 Facebook Connect 作为用户注册和身份验证的一个路径,但我没有找到太多关于如何获取和解析 FB cookie 甚至正确流程的信息.我正在尝试将官方文档中的信息与这个 但对于 Java.我不反对依赖像 Social Java 这样的库,但了解这些步骤会有所帮助.以下是我想要满足的 3 个用例.

I'm building a JSP application and I would like to use Facebook Connect as one path for user registration and authentication, but I'm not finding much information about how to fetch and parse the FB cookie or even the right flow. I'm trying to merge the information found in the official documentation with a step by step guide like this one but for Java. I am not opposed to relying on libraries like Social Java but understanding the steps would be helpful. Here are the 3 use cases I'm trying to satisfy.

  1. 我网站上未经身份验证/未注册的用户点击Facebook Connect"按钮进行注册(获取电子邮件、姓名和个人资料 ID)并登录.
  2. 未经身份验证的用户点击Facebook Connect"按钮在我的域上创建有效会话.
  3. 经过身份验证和注册且未连接 Facebook 个人资料的用户点击Facebook Connect"并将 Facebook 个人资料 ID(以及更新其电子邮件和姓名的选项)与其现有个人资料相关联.

对于这个项目,我有一个像这样的 Profile 类(我正在使用优秀的 Project Lombok 和 Hibernate)

For this project I have a Profile class that looks like this (I'm using the excellent Project Lombok with Hibernate)

@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;
}

Status 和 Level 真的应该是枚举,但我试图让这个问题的代码很小.

Status and Level really should be enums, but I'm trying to keep the code tiny for this question.

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

Disclaimer:I've been reading a lot of blogs about how to setup Facebook Connect for user registration and authentication, but they are for the most part based on PHP and older versions of the Facebook API (even some SO questions point to the old wiki in their accepted answers). This seems like a perfect application of the SO community.

推荐答案

这是我使用的 servlet 解决方案.只需稍加调整,您就可以使用简单的用户名-密码形式让它在任何 JSP 中工作.不需要javascript!!!至于地址和电话号码,请阅读以下内容:http://developers.facebook.com/blog/post/447

Here is servlet solution I use. With little tweaking you can meke it work in any JSP with simple username-password form. No javascript needed!!! As far as address and phone number go read this: http://developers.facebook.com/blog/post/447

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;
}
}

这篇关于JSP 中的 Facebook Connect 示例(tomcat)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆