没有重定向的Spring安全性

时间:2014-10-24 19:08:01

标签: java spring spring-security

我有一个无状态的Spring Security实现,并使用基于令牌的身份验证。我的大多数逻辑都存在于扩展AbstractAuthenticationProcessingFilter的类中。我的问题是,在身份验证成功后,AbstractAuthenticationProcessingFilter执行302重定向,这是我不想要的。我只想要完成原始请求。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

我能够通过覆盖成功和失败处理程序使spring security公开的“login”rest方法返回“200 OK”而不是“302 Redirect”。 下面的代码显示了如何实现相同的目标。

        //configure http by using the successHandler 
        //and failure handler methods
        http.
            formLogin()
                .loginPage("/authentication/login")
                .loginProcessingUrl("/authentication/processLogin")
                .successHandler(successHandler())
                .failureHandler(failureHandler())
            .and()
            ......



    private AuthenticationFailureHandler failureHandler() {
        return new SimpleUrlAuthenticationFailureHandler() {
            public void onAuthenticationFailure(HttpServletRequest request,
                    HttpServletResponse response, AuthenticationException exception)
                    throws IOException, ServletException {
                response.setContentType("text/html;charset=UTF-8");
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Failed. Wrong username or password or both");
            }
        };
    }


    private AuthenticationSuccessHandler successHandler() {
        return new SimpleUrlAuthenticationSuccessHandler() {
            public void onAuthenticationSuccess(HttpServletRequest request,
                    HttpServletResponse response, Authentication authentication)
                    throws IOException, ServletException {
                response.setContentType("text/html;charset=UTF-8");
                HttpSession session = request.getSession(false);
                session.setMaxInactiveInterval(60*180);
                response.getWriter().println("LoginSuccessful");
            }
        };
    }