Spring Security 6.0下无法进入H2-Console控制台的问题咨询
问题分析
调试日志显示POST /h2-console/login.do请求触发CSRF token无效的403错误,核心原因是Spring Security 6.0默认使用MvcRequestMatcher匹配路径,而H2-Console的请求由自身Servlet处理,不属于Spring MVC的DispatcherServlet管辖,导致你配置的csrf.ignoringRequestMatchers("/h2-console/**")无法正确匹配H2的请求,CSRF保护仍对该请求生效。
解决方案
修改CSRF配置,显式使用AntPathRequestMatcher匹配H2路径(它基于Servlet路径匹配,不受请求处理方式限制),同时确保授权规则也用该匹配器覆盖H2路径,具体配置如下:
import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(authorizeRequests -> authorizeRequests .requestMatchers(new AntPathRequestMatcher("/h2-console/**")).authenticated() .anyRequest().authenticated() ) .formLogin(formLogin -> formLogin .permitAll() ) .csrf(csrf -> csrf .ignoringRequestMatchers(new AntPathRequestMatcher("/h2-console/**"))) .headers(headers -> headers .frameOptions().sameOrigin()); return http.build(); }
额外说明
- 移除你之前配置的
WebSecurityCustomizer,它会完全跳过H2路径的所有安全检查,不符合你需要认证后访问H2的需求。 frameOptions().sameOrigin()配置保留,确保H2的iframe能正常渲染。
内容的提问来源于stack exchange,提问作者JJJohn
相关产品推荐
相关产品推荐

