React与Spring Boot登出功能异常:405错误及会话问题求助
问题分析与解决方案
问题根源
你遇到的GET http://localhost:8080/login?logout 405错误,本质是Spring Security的默认登出逻辑和你自定义的登出接口冲突:
- Spring Security自带默认的
LogoutFilter,会拦截/logout请求(无论请求方法),执行内置的登出流程:销毁会话、重定向到/login?logout地址。 - 你的自定义
@PostMapping("/logout")控制器并没有实际被执行,反而触发了Spring Security的默认重定向,而你的后端没有提供GET方法的/login接口,因此出现405(方法不允许)错误。 - 刷新页面会话消失,是因为Spring Security的默认登出流程已经销毁了会话,这部分是生效的,但重定向环节出了问题。
解决步骤
1. 禁用Spring Security默认登出逻辑
在Spring Security配置类中,禁用默认的登出过滤器,让你的自定义控制器接口生效:
@Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http // 禁用默认登出逻辑 .logout(logout -> logout.disable()) // 配置跨域支持 .cors(cors -> cors.configurationSource(corsConfigurationSource())) // 配置CSRF,支持带凭证的跨域POST请求 .csrf(csrf -> csrf .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) ); return http.build(); } // 配置跨域规则,允许React前端的请求 @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(List.of("http://localhost:3000")); config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS")); config.setAllowedHeaders(List.of("*")); config.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return source; } }
2. 修复React端的CSRF Token传递
Spring Security默认启用CSRF保护,带withCredentials: true的POST请求必须携带CSRF Token才能通过校验。修改你的handleLogout函数,从Cookie中获取CSRF Token并添加到请求头:
const handleLogout = async () => { try { // 从Cookie中提取CSRF Token const getCookie = (name) => { const value = `; ${document.cookie}`; const parts = value.split(`; ${name}=`); if (parts.length === 2) return parts.pop().split(';').shift(); }; const csrfToken = getCookie('XSRF-TOKEN'); const response = await axios.post('http://localhost:8080/logout', {}, { withCredentials: true, headers: { 'X-XSRF-TOKEN': csrfToken } }); console.log(response.data); window.location.href = "http://localhost:3000/login"; } catch (error) { console.error('Fail to Logout', error); } };
3. 验证效果
此时点击登出按钮,会触发你自定义的Spring Boot控制器:销毁会话,返回成功响应,然后React端跳转到http://localhost:3000/login,不会再出现8080端口的GET请求错误。
内容的提问来源于stack exchange,提问作者im2ho
相关产品推荐
相关产品推荐

