После успешного входа URL-адрес снова перенаправляется на /login

Я новичок в Spring boot, у меня есть небольшое приложение, использующее Spring Boot и Spring Security. После успешного входа страница снова перенаправляется на /login. Я не знаю, как это исправить.

После успешного входа:

введите здесь описание изображения

Это конфигурация безопасности:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/", "/login").permitAll()//设置SpringSecurity对"/"和"/login"路径不拦截
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")//设置Spring Security的登录页面访问路径为/login
                .defaultSuccessUrl("/chat")//登录成功后转向/chat路径
                .permitAll()
                .and()
                .logout()
                .permitAll();


    }

    /**
     * 在内存中分别配置两个用户xin.luo和king.luo,密码和用户名一致,角色是USER
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("xin").password("xin").roles("USER")
                .and()
                .withUser("king").password("king").roles("USER");
    }

    /**
     * /resources/static/目录下的静态资源文件,Spring Security不拦截
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/static/**");
    }
}

person Xin_Law    schedule 01.11.2017    source источник
comment
Что у вас есть на стороне клиента? И знаете ли вы наверняка, прошла ли аутентификация успешно?   -  person br.julien    schedule 01.11.2017
comment
Вот моя страница входа, я думаю, что аутентификация прошла успешно. Но страница снова перенаправляется на /login после перенаправления с /login на /chat, как на диаграмме выше. ‹body› ‹div th:if=${param.error}› 无效账号和密码 ‹/div› ‹div th:if=${param.logout}› 你已注销 ‹/div› ‹form th:action= @{/login} method=post› ‹div›‹label›账号:‹input type=text name=username/›‹/label›‹/div› ‹div›‹label›密码:‹input type=password name= пароль/›‹/метка›‹/div› ‹div›‹тип ввода=отправить значение=登录/›‹/div› ‹/form› ‹/body›   -  person Xin_Law    schedule 02.11.2017


Ответы (2)


Какое поведение вам нужно? По сути, есть два варианта: перенаправить на какое-то статичное, известное место, например /index, или перенаправить на изначально запрошенную страницу. Оба требуют настройки AuthenticationSuccessHandler. Вы также можете использовать/расширить один из существующих обработчиков авторизации для выполнения некоторых основных задач. Например, обратите внимание, как SimpleUrlAuthenticationSuccessHandler можно использовать для перенаправления на изначально запрошенную страницу:

Конфигурация безопасности XML:

<http use-expressions="true">
    <intercept-url pattern="/login*" access="permitAll"/>
    <intercept-url pattern="/**" access="isAuthenticated()"/>

    <form-login
        ...
        authentication-success-handler-ref="authenticationSuccessHandler"

        authentication-success-handler-ref="refererAuthenticationSuccessHandler"
        ...
        />

    <logout/>
</http>

<!-- Route users to their profiles and admins to the admin console: -->
<beans:bean id="authenticationSuccessHandler" class="a.b.c.AuthenticationSuccessHandler"/>

<!-- Route to the originally requested page -->
<beans:bean id="refererAuthenticationSuccessHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler">
    <property name="useReferer" value="true"/>
</beans:bean>

Пример AuthenticationSuccessHandler:

public class AuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        // Very simple (most probably broken) check if the user is ADMIN or USER
        if (authentication.getAuthorities().stream().filter(a -> a.getAuthority().equals("USER")).findAny() != null){
            redirectStrategy.sendRedirect(request, response, "/profile.html");
        } else {
            redirectStrategy.sendRedirect(request, response, "/admin.html");
        }

        clearAuthenticationAttributes(request);
    }
}
person madhead    schedule 01.11.2017
comment
Спасибо за помощь. В этом приложении я хочу перенаправить страницу с /login на /chat после успешного входа в систему. Я установил успешный URL-адрес по умолчанию в WebSecurityConfig.java, но страница перенаправляется на /chat, а затем снова перенаправляется на /login, как на диаграмме выше. - person Xin_Law; 02.11.2017

Может быть и другая возможность. Файл cookie не был установлен, и все последующие отправленные запросы обрабатывались как первый запрос без идентификатора сеанса.

Если вы использовали Google Chrome и тестировали приложение на своем локальном компьютере, используя адрес локального хоста, файл cookie мог быть не установлен. вы можете увидеть более подробную информацию здесь: Chrome localhost cookie не устанавливается

Вместо этого вы можете попробовать 127.0.0.1 для проверки.

person bob tang    schedule 04.03.2020