成功登录后,Spring Boot重定向到当前页面

set*_*812 11 spring spring-security spring-boot

我在模态窗口中有登录表单.登录成功后,用户将被重定向到/页面.我正在尝试找到一种方法,以便在登录后留在联系页面或其他页面上.这该怎么做?我的代码是:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers("/css/**","/js/**","/fonts/**","/images/**","/home","/","/kontakt").permitAll()
            .antMatchers("/userlist").hasRole("ADMIN")
            .anyRequest().authenticated();
    http
        .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
        .logout()
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .logoutSuccessUrl("/");
}
Run Code Online (Sandbox Code Playgroud)

Boh*_*rdt 17

您可以使用自定义AuthenticationSuccessHandler并设置useReferertrue.

@Bean
public AuthenticationSuccessHandler successHandler() {
    SimpleUrlAuthenticationSuccessHandler handler = new SimpleUrlAuthenticationSuccessHandler();
    handler.setUseReferer(true);
    return handler;
}
Run Code Online (Sandbox Code Playgroud)

在你的configure方法中:

http
    .formLogin()
        .loginPage("/login")
        .successHandler(successHandler())
        .permitAll()
        .and()
Run Code Online (Sandbox Code Playgroud)


小智 10

只是为了提供替代解决方案:

formLogin()
    .loginPage("/login")
    .defaultSuccessUrl("/")
Run Code Online (Sandbox Code Playgroud)

defaultSuccessUrl是添加自定义的快捷方式SuccessHandler.

  • 您的答案与问题的当前版本不匹配。你的答案是有缺陷的,“defaultSuccessUrl”是“SavedRequestAwareAuthenticationSuccessHandler”的快捷方式,而不是自定义“SuccessHandler”的快捷方式。 (2认同)

ben*_*bia 6

我有一个奇怪的问题会导致登录时将用户重定向到 localhost:8080/js/bootstrap.min.js

如果其他人在登录时遇到奇怪的重定向,这似乎覆盖了.defaultSuccessUrl(),然后尝试在下面添加此代码SecurityConfig

@Override
public void configure(WebSecurity security){
    security.ignoring().antMatchers("/css/**","/images/**","/js/**");
}
Run Code Online (Sandbox Code Playgroud)

将所有Resources/static文件夹添加到antMatchers()


Aug*_*tto 5

你也可以在你的AuthenticationSuccessHandler实现中做到这一点:

@Override
public void onAuthenticationSuccess(HttpServletRequest request, 
HttpServletResponse response, Authentication authentication) throws 
IOException, ServletException 
{
    //Do your logic;
    response.sendRedirect(request.getHeader("referer");
}
Run Code Online (Sandbox Code Playgroud)