You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3中无法将h2-console URL加入白名单的问题

解决Spring Security下无法访问H2控制台的问题

你的配置存在几个关键问题,导致H2控制台无法正常访问,修改后的完整配置如下:

@Configuration
@EnableWebSecurity(debug = true)
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                // 配置请求授权规则
                .authorizeRequests(authorizeRequests -> authorizeRequests
                        .requestMatchers(antMatcher("/h2-console/**")).permitAll()
                        .anyRequest().authenticated())
                // 启用HTTP Basic认证
                .httpBasic(withDefaults())
                // 禁用CSRF(H2控制台不需要CSRF保护)
                .csrf(csrf -> csrf.disable())
                // 允许H2控制台的iframe加载,解除X-Frame-Options限制
                .headers(headers -> headers.frameOptions(frameOptions -> frameOptions.sameOrigin()))
                // 添加自定义过滤器
                .addFilterBefore(new ProductFilter(), BasicAuthenticationFilter.class);
        return http.build();
    }
}

关键修改点说明:

  • 移除重复的CSRF配置:你之前同时写了ignoringRequestMatchers和disable,统一使用csrf.disable()即可,避免配置冲突。
  • 添加frameOptions配置:H2控制台依赖iframe渲染内容,Spring Security默认会设置X-Frame-Options: DENY阻止iframe加载,设置为sameOrigin允许同域的iframe正常显示。
  • 确保路径匹配正确:/h2-console/**的匹配规则已经覆盖了H2控制台的所有子路径,无需额外调整。

如果修改后仍然无法访问,建议检查:

  • 项目配置文件中H2控制台的路径是否为/h2-console(比如spring.h2.console.path属性)。
  • 自定义的ProductFilter是否拦截了/h2-console路径的请求,可临时注释过滤器测试。

内容的提问来源于stack exchange,提问作者Arindam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 03:58:22