Spring Boot 3.0.2集成Spring Security时如何访问H2-console?
Spring Boot 3.0.2 + Spring Security 下 H2 控制台 403 问题解决
我在基于 Spring Boot 3.0.2 和 Java 17 的项目中集成了 Spring Security,配置了无需令牌即可访问的白名单(如 /register、/api/v1/getUsers),这些 URL 都能正常访问,但 /h2-console 始终返回 403 未授权错误。尝试过在 HttpSecurity 中通过 permitAll() 配置,完全没用,最后通过添加 WebSecurityCustomizer 忽略该 URL 的安全校验才解决问题。
解决方案
核心是用 WebSecurityCustomizer 直接绕过 Spring Security 对 H2 控制台路径的拦截,而非在 HttpSecurity 中做放行配置。
完整代码示例
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth // 其他白名单配置 .requestMatchers("/register", "/api/v1/getUsers").permitAll() .anyRequest().authenticated() ) // H2 控制台需要关闭 CSRF 防护,否则操作会被拦截 .csrf(csrf -> csrf.disable()); return http.build(); } // 关键:忽略 H2 控制台所有路径的安全校验 @Bean public WebSecurityCustomizer webSecurityCustomizer() { return web -> web.ignoring() .requestMatchers(AntPathRequestMatcher.antMatcher("/h2-console/**")); } }
额外注意事项
别忘了在配置文件中开启 H2 控制台:
# application.properties spring.h2.console.enabled=true spring.h2.console.path=/h2-console spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=sa spring.datasource.password=
内容的提问来源于stack exchange,提问作者SpEcTaCuLaR
相关产品推荐
相关产品推荐

