Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

model view controller - ajax login with spring webMVC and spring security

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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") {
            ...
        }
    }
});

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...