无需重定向的 Spring 安全性

问题描述 投票:0回答:2

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

java spring spring-security
2个回答
6
投票

通过覆盖成功和失败处理程序,我能够使 Spring Security 公开的“登录”休息方法返回“200 OK”而不是“302 重定向”。 下面的代码展示了如何实现相同的目的。

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

0
投票

我在编写自定义身份验证机制时遇到了这个问题,据我了解,当通过扩展

AbstractAuthenticationProcessingFilter
来编写自定义过滤器来执行自定义身份验证操作,并在安全配置上使用此过滤器时,我需要覆盖我的过滤器上的
successfulAuthentication
方法(只需写
chain.dofilter(req,resp)
),因为默认行为似乎总是使用重定向。现在我不知道这是因为某些安全问题,但出于我的需要,我以这种方式禁用了重定向,并想分享。祝你有美好的一天😊!

© www.soinside.com 2019 - 2024. All rights reserved.