How to set redirection after successful login?

Defining the redirection after a successful login needs to be applied on Spring Security, not Spring MVC.

The th:action defines the Spring Security endpoint that will process the authentication request. It does not define the redirection URL. Out of the box, Spring Boot Security will provide you the /login endpoint. By default, Spring Security will redirect after login to the secured ressource you tried to access. If you wish to always redirect to a specific URL, you can force that through the HttpSecurity configuration object.

Assuming you are using a recent version of Spring Boot, you should be able to use JavaConfig.

Here is a simple exemple :

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // the boolean flags force the redirection even though 
        // the user requested a specific secured resource.
        http.formLogin().defaultSuccessUrl("/success.html", true);
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService);
    }
}

Please note that you need to define a proprer endpoint to serve content for the /success.html URL. A static resource available by default in src/main/resources/public/ would do the trick for test purpose. I would personnally rather define a secured URL served by a Spring MVC Controller serving content with Thymeleaf. You don't want any anonymous user to be able to access the success page. Thymeleaf as some usefull features to interact with Spring Security while rendering the HTML content.

Regards, Daniel


It works for me. Once the login has been successful, Spring security redirects to "/" and then, I checks if the user is authenticated and in this case, redirects it to my dashboard page.

@RequestMapping("/")
    public String index(Model model) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (!(auth instanceof AnonymousAuthenticationToken))
            return "dashboard";

        // if it is not authenticated, then go to the index...
        // other things ...
        return "index";
    }