Spring Security+Thymeleaf登出配置404问题排查求助
患者模块登出404问题排查要点
1. 核对Security Config的登出配置
Spring Security默认登出端点是/logout,配置必须准确:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http // 其他登录、权限配置... .logout() .logoutUrl("/logout") // 必须和前端表单action一致 .logoutSuccessUrl("/login?logout") // 登出成功跳转页 .invalidateHttpSession(true) .deleteCookies("JSESSIONID"); } }
- 注意
logoutUrl的路径要和前端完全匹配,别漏了项目上下文路径(如果有的话)。 - Spring Security默认只接受POST请求的登出,用GET请求会直接返回404。
2. 检查前端登出表单的写法
前端必须用POST方式提交,action指向正确端点:
<form th:action="@{/logout}" method="post"> <button type="submit">登出</button> </form>
- 别用
<a href="/logout">这种GET链接,这是最常见的踩坑点。 - 用Thymeleaf的
@{/logout}能自动处理上下文路径,避免路径错误。
3. 排查Controller的路径冲突
别自己写/logout的Controller映射,会覆盖Spring Security的默认端点:
// 这种代码要删掉! @GetMapping("/logout") public String logout() { return "logout"; }
4. 匹配Spring Security版本的配置写法
如果用Spring Boot 3.x,要改用SecurityFilterChain配置,不能再用WebSecurityConfigurerAdapter:
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http // 其他配置... .logout(logout -> logout .logoutUrl("/logout") .logoutSuccessUrl("/login?logout") .invalidateHttpSession(true) .deleteCookies("JSESSIONID") ); return http.build(); }
核对pom.xml里的spring-boot-starter-security版本,确保配置写法对应。
5. 确认CSRF令牌的处理
Spring Security默认开了CSRF防护,Thymeleaf表单会自动生成令牌,但手动写的表单要加:
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
如果测试时要临时关闭CSRF(生产环境别这么做),就在Security Config里加:
http.csrf().disable();
内容的提问来源于stack exchange,提问作者Johndavid Cabal
相关产品推荐
相关产品推荐

