В весенней безопасности 4 одновременный сеанс не перенаправляется на просроченный URL-адрес

В весенней безопасности 4 параллельный сеанс не перенаправляется на просроченный URL-адрес, вместо этого он перенаправляется на URL-адрес неудачной аутентификации. Ниже приведен фрагмент кода конфигурации Java.

/*start of code*/
public class SecurityContextConfig extends WebSecurityConfigurerAdapter {

private static final Logger logger = LoggerFactory.getLogger(SecurityContextConfig.class);

/**
 * @param auth
 * @throws Exception
 */
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    logger.debug("configureGlobal() : Start : auth={}", auth);
    auth.authenticationProvider(userDetailsAuthenticationProvider());
}

@Override
public void configure(WebSecurity web) throws Exception {
    logger.debug("configure() : Start : web={}", web);
    // This is here to ensure that the static content (JavaScript, CSS, etc)
    // is accessible from the login page without authentication
    web.ignoring().antMatchers("/resources/**");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    logger.debug("configure() : Start : http={}", http);

    http
        .authorizeRequests()
            .antMatchers("/resources/**")
                .permitAll()
            .antMatchers("/login/**")
                .permitAll()
            .antMatchers("/authenticate/**")
                .permitAll()
            .antMatchers("/ssoLogout")
                .permitAll()
            .antMatchers("/forgotpassword/json")
                .permitAll()
            .antMatchers("/favicon.ico")
                .permitAll()
            .antMatchers("/secure/**")
                .authenticated()
            .and()

            // This is where we configure our login form.
            // login-page: the page that contains the login screen
            // login-processing-url: this is the URL to which the login form
            // should be submitted
            // default-target-url: the URL to which the user will be
            // redirected if they login successfully
            // authentication-failure-url: the URL to which the user will be
            // redirected if they fail login
            // username-parameter: the name of the request parameter which
            // contains the username
            // password-parameter: the name of the request parameter which
            // contains the password
            .formLogin()
                .loginPage("/")
                .loginProcessingUrl("/authenticate")
                .failureUrl("/")
                .successHandler(loginSuccessHandler())
            .and()

            // This is where the logout page and process is configured. The
            // logout-url is the URL to send
            // the user to in order to logout, the logout-success-url is
            // where they are taken if the logout
            // is successful, and the delete-cookies and invalidate-session
            // make sure that we clean up after logout
            .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(logoutHandler())
                .deleteCookies("JSESSIONID")
                .invalidateHttpSession(true)
            .and()

            .csrf()
            .and()

            // The session management is used to ensure the user only has
            // one session. This isn't
            // compulsory but can add some extra security to your
            // application.
            .sessionManagement()
                //.invalidSessionUrl("/login")
                .sessionFixation()
                .changeSessionId()
            .maximumSessions(1)
                .expiredUrl("/login?reason=CONCURRENT_SESSION");
            http.exceptionHandling().accessDeniedHandler(accessDeniedHandler());
    logger.debug("configure() : End : http={}", http);

}

/**
 * @return
 */
@Bean(name = "loginSuccessHandler")
public LoginSuccessHandler loginSuccessHandler() {
    logger.debug("loginSuccessHandler() : Start.");
    LoginSuccessHandler loginSuccessHandler = new LoginSuccessHandler();

    logger.debug("loginSuccessHandler() : End : loginSuccessHandler={}", loginSuccessHandler);
    return loginSuccessHandler;}

/**
 * @return
 */
@Bean(name = "logoutHandler")
public LogoutHandler logoutHandler() {
    logger.debug("logoutHandler() : Start.");

    LogoutHandler logoutHandler = new LogoutHandler();

    logger.debug("logoutHandler() : End : logoutHandler={}", logoutHandler);

    return logoutHandler;
}

/**
 * @return
 */
@Bean(name = "authenticationProvider")
public UserDetailsAuthenticationProvider userDetailsAuthenticationProvider() {
    logger.debug("userDetailsAuthenticationProvider() : Start.");

    UserDetailsAuthenticationProvider authenticationProvider = new UserDetailsAuthenticationProvider();

    logger.debug("userDetailsAuthenticationProvider() : End : authenticationProvider={}", authenticationProvider);

    return authenticationProvider;
}

@Bean(name="accessDeniedHandler")
public AccessDeniedHandlerImpl accessDeniedHandler(){

AccessDeniedHandlerImpl accessDeniedHandler=new AccessDeniedHandlerImpl();
accessDeniedHandler.setErrorPage("/login?reason=Access Denied");
    return accessDeniedHandler;

}}

Поведение просроченного URL непоследовательно. Иногда работает, но иногда не работает. В чем может быть проблема?


person Viral B    schedule 10.08.2015    source источник


Ответы (1)


Проблема в том, что когда он перенаправляется на URL-адрес с истекшим сроком действия, ваш пользователь не имеет доступа к URL-адресу, поэтому он отправляет пользователя на страницу входа в систему (которая совпадает с URL-адресом ошибки входа в систему).

Вы должны убедиться, что вы предоставляете доступ каждому пользователю к просроченному URL-адресу. Например:

http
    .authorizeRequests()
        .antMatchers("/login")
            .permitAll()
        ...
person Rob Winch    schedule 10.08.2015
comment
Этого нет в предоставленном вами коде (ПРИМЕЧАНИЕ, это /login, а не /login/**). Если у вас есть это в коде, который вы используете, пожалуйста, обновите свой пост. - person Rob Winch; 11.08.2015