使用 spring webMVC 和 spring security 进行 ajax 登录 [英] ajax login with spring webMVC and spring security

查看:54
本文介绍了使用 spring webMVC 和 spring security 进行 ajax 登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 Spring Security 3.0 作为我们使用专用登录网页的网站登录机制.现在我需要该登录网页成为我们网站中每个网页上的灯箱/弹出窗口,在登录时,无论成功与否,我都会得到 AJAX 结果.使用 Spring Security 和 Spring webmvc 3.0 解决此问题的最佳方法是什么?

I've been using Spring Security 3.0 for our website login mechanism using a dedicated login webpage. Now I need that login webpage to instead be a lightbox/popup window on every webpage in our site where upon logging in I get an AJAX result whether it was successful or not. What's the best way to go about this with Spring Security and Spring webmvc 3.0?

推荐答案

在客户端,您可以通过 ajax 模拟向登录 url 提交的正常表单.例如,在 jQuery 中:

At the client-side you may simulate a normal form submission to your login url via ajax. For example, in jQuery:

$.ajax({
    url: "${pageContext.request.contextPath}/j_spring_security_check",
    type: "POST",
    data: $("#loginFormName").serialize(),
    beforeSend: function (xhr) {
        xhr.setRequestHeader("X-Ajax-call", "true");
    },
    success: function(result) {
        if (result == "ok") {
            ...
        } else if (result == "error") {
            ...
        }
    }
});

在服务器端,您可以自定义AuthenticationSuccessHandlerAuthenticationFailureHandler 以返回值而不是重定向.因为您可能还需要一个普通的登录页面(为了尝试通过直接 url 访问安全页面),所以您应该告诉 ajax 调用来自普通调用,例如,使用 header:

At the server side, you may customize AuthenticationSuccessHandler and AuthenticationFailureHandler to return a value instead of redirect. Because you probably need a normal login page as well (for attempt to access a secured page via direct url), you should tell ajax calls from normal calls, for example, using header:

public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private AuthenticationSuccessHandler defaultHandler;

    public AjaxAuthenticationSuccessHandler() {

    }
    public AjaxAuthenticationSuccessHandler(AuthenticationSuccessHandler defaultHandler) {
        this.defaultHandler = defaultHandler;
    }

    public void onAuthenticationSuccess(HttpServletRequest request,
        HttpServletResponse response, Authentication auth)
        throws IOException, ServletException {
    if ("true".equals(request.getHeader("X-Ajax-call"))) {
        response.getWriter().print("ok");
        response.getWriter().flush();
    } else {
        defaultHandler.onAuthenticationSuccess(request, response, auth);
    }
}
}

这篇关于使用 spring webMVC 和 spring security 进行 ajax 登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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