成功登录后,Spring Security有时会重定向到默认页面而不是登录前页面

时间:2020-01-21 06:12:05

标签: java spring spring-boot spring-security

我们的团队正在使用Spring Boot(2.2.2)开发Web应用程序。它使用Spring安全性来处理登录过程。我们希望应用程序在登录之前重定向回页面(例如,用户访问权限http://example.com/foo/bar->如果登录会话已过期,则显示登录页面->如果登录成功,则直接回到http://example.com/foo/bar)< / p>

一切似乎都很好,只是应用程序偶尔会定向到默认页面(例如http://example.com),而不是登录前的页面。发生这种情况时,登录之前的页面似乎未保存在会话中(根据我的队友的报告)。这是由于我们的配置问题造成的吗?

以下是我们的WebSecurityConfig

@Override
    public void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("...")
            .anyRequest().authenticated()
        .and()
        .csrf().ignoringAntMatchers("...")
        .and()
        .formLogin()
            .loginPage("/loginForm")
            .loginProcessingUrl("/login")
            .usernameParameter("userId")
            .passwordParameter("password")
            .failureUrl("/loginForm?error=true")
            .permitAll()
        .and()
        .logout()
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .logoutSuccessHandler(logoutSuccessHandler())
            .deleteCookies("JSESSIONID")
            .invalidateHttpSession(true)
            .permitAll()
        .and()
        .exceptionHandling()
            .accessDeniedHandler(new CustomAccessDeniedHandler())
        .and()
        .sessionManagement()
            .invalidSessionUrl("/loginForm")
            ;
    }

由于未在WebSecurityConfig中设置successHandler,因此默认情况下将调用SavedRequestAwareAuthenticationSuccessHandler。 onAuthenticationSuccess 方法的以下部分似乎出现了问题:

@Override
public void onAuthenticationSuccess(HttpServletRequest request,
        HttpServletResponse response, Authentication authentication)
        throws ServletException, IOException {
    SavedRequest savedRequest = requestCache.getRequest(request, response);

    if (savedRequest == null) {
        super.onAuthenticationSuccess(request, response, authentication);
        return;
    }
    String targetUrlParameter = getTargetUrlParameter();
    if (isAlwaysUseDefaultTargetUrl()
            || (targetUrlParameter != null && StringUtils.hasText(request
                        .getParameter(targetUrlParameter)))) {
        requestCache.removeRequest(request, response);
        super.onAuthenticationSuccess(request, response, authentication);
        return;
    }

    clearAuthenticationAttributes(request);

    // Use the DefaultSavedRequest URL
    String targetUrl = savedRequest.getRedirectUrl();
    logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
    getRedirectStrategy().sendRedirect(request, response, targetUrl);
}

有时,saveRequest为null,因此成功登录后,Spring安全性将定向到默认页面(http://example.com)。是什么原因?

1 个答案:

答案 0 :(得分:0)

重定向到上下文根是由于sessionManagement().invalidSessionUrl("/loginForm")引起的。

这是因为您正在显式调用登录页面,因此将其视为请求的页面,而不是重定向到身份验证。身份验证后,spring将重定向到默认url(默认情况下为上下文根,除非在配置中被覆盖)。

在我看来,这应该总是发生,而不是偶尔发生。

请删除上述配置,并让spring处理重定向以进行身份​​验证。 :)