Spring Security 5.7.11自定义/login后/logout GET请求失效问题
问题解决:Spring Security网关中恢复/logout的GET请求行为并保证注销生效
问题原因
添加自定义RedirectServerAuthenticationEntryPoint后,Spring Security默认注销配置被覆盖,原本支持的GET /logout请求匹配器被移除,导致仅接受POST请求;同时自定义配置还可能影响会话清除与注销成功处理器的执行逻辑。
解决方案
修改SecurityWebFilterChain配置,显式开启GET /logout支持,同时配置会话清除与自定义注销成功处理器:
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { // 自定义注销成功处理器,处理RP发起的注销逻辑 ServerLogoutSuccessHandler logoutSuccessHandler = (exchange, authentication) -> { // 此处添加注销成功后的业务逻辑,比如重定向到登录页、通知相关服务等 exchange.getResponse().setStatusCode(HttpStatus.SEE_OTHER); exchange.getResponse().getHeaders().setLocation(URI.create("/login")); return Mono.empty(); }; http .authorizeExchange(authorizeExchangeSpec -> authorizeExchangeSpec .pathMatchers("/login", "/logout").permitAll() // 允许未认证访问注销接口 .anyExchange().authenticated() ) .formLogin().disable() .csrf().disable() .oauth2Login() .and() .logout(logoutSpec -> logoutSpec .logoutUrl("/logout") .logoutRequestMatcher(ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, "/logout")) // 显式指定GET请求匹配规则 .logoutSuccessHandler(logoutSuccessHandler) // 绑定自定义注销成功处理器 .deleteCookies("JSESSIONID") // 清除会话关联Cookie .invalidateHttpSession(true) // 强制失效当前Http会话 ) .exceptionHandling(exceptionHandlingSpec -> exceptionHandlingSpec.authenticationEntryPoint(new RedirectServerAuthenticationEntryPoint("/login")) ); return http.build(); }
关键配置说明
logoutRequestMatcher:显式指定GET /logout作为注销请求的匹配规则,覆盖默认仅支持POST的配置。permitAll()添加/logout:避免注销操作还需前置认证的问题,允许未认证用户访问注销接口。invalidateHttpSession(true):强制失效当前Http会话,确保会话信息被彻底清除。deleteCookies:清除客户端存储的会话Cookie,杜绝残留会话信息。logoutSuccessHandler:自定义注销成功后的处理逻辑,满足RP发起的注销需求。
验证
配置完成后,访问GET /logout即可触发注销操作,日志不再出现请求不匹配的错误,同时会话会被正常清除,注销成功处理器也会执行预设逻辑。
内容的提问来源于stack exchange,提问作者Q2Dev
相关产品推荐
相关产品推荐

