在成功登录后定义重定向需要在Spring Security而非Spring MVC上应用。
该
th:action定义Spring Security的端点将处理认证请求。它没有定义重定向URL。开箱即用,Spring Boot
Security将为您提供
/login端点。默认情况下,Spring
Security将在登录后重定向到您尝试访问的安全资源。如果希望始终重定向到特定的URL,则可以通过HttpSecurity配置对象强制执行该操作。
假设您使用的是Spring Boot的最新版本,则应该能够使用JavaConfig。
这是一个简单的例子:
@Configuration@EnableWebSecuritypublic 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); }}请注意,您需要定义一个适当的终结点来提供
/success.htmlURL的内容。默认情况下,可用的静态资源可以
src/main/resources/public/完成测试目的。我个人更希望定义一个由Thyeleaf提供内容的Spring
MVC Controller提供的安全URL。您不希望任何匿名用户都能访问成功页面。Thymeleaf是在呈现HTML内容时与Spring
Security交互的一些有用功能。
问候,丹尼尔



