在Spring Boot项目中使用H2内存数据库进行开发时,H2自带的Web控制台是非常实用的调试工具,但引入Spring Security后,默认的权限管控规则会将H2控制台的访问请求拦截,导致无法直接使用相关功能。要正确实现H2控制台免认证访问,需要针对Spring Security的过滤规则和路径放行做针对性配置。

前置依赖确认
首先需要确保项目中已经引入了必要的依赖,H2数据库依赖和Spring Security依赖都是必须的,示例的Maven依赖配置如下:
<dependencies>
<!-- H2数据库依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Spring Security依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
核心配置步骤
1. 开启H2控制台配置
需要在Spring Boot的配置文件中开启H2控制台的访问权限,application.yml的配置示例如下:
spring:
h2:
console:
enabled: true
path: /h2-console
datasource:
url: jdbc:h2:mem:testdb
driver-class-name: org.h2.Driver
username: sa
password:
2. 配置Spring Security放行规则
Spring Security默认会拦截所有请求,需要针对H2控制台的相关路径做放行处理,同时还需要关闭H2控制台相关的CSRF防护和FrameOptions限制,否则会出现页面无法加载或者操作被拦截的问题。完整的Security配置类示例如下:
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.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
// 关闭CSRF防护,H2控制台的相关请求不需要CSRF校验
.csrf(AbstractHttpConfigurer::disable)
// 配置请求授权规则
.authorizeHttpRequests(auth -> auth
// 放行H2控制台相关路径
.requestMatchers("/h2-console/**").permitAll()
// 其他请求需要认证
.anyRequest().authenticated()
)
// 关闭X-Frame-Options限制,H2控制台页面使用iframe加载内容
.headers(headers -> headers.frameOptions(frame -> frame.disable()));
return http.build();
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
// 忽略H2控制台相关路径的Security过滤,避免被拦截
return web -> web.ignoring().requestMatchers("/h2-console/**");
}
}
配置验证
完成上述配置后,启动Spring Boot项目,访问/h2-console路径,输入配置文件中设置的JDBC URL、用户名和密码,就可以直接进入H2控制台操作数据库,不需要进行额外的登录认证。
注意事项
- 上述配置仅适用于开发环境,生产环境绝对不能开启H2控制台,也不能做类似的免认证配置,避免造成数据安全风险。
- 如果修改了H2控制台的访问路径,需要调整Security配置中的放行路径,保证两者一致。
- 如果项目中使用了其他的安全规则,需要确保H2控制台的放行规则优先级高于其他拦截规则,避免被其他规则覆盖。
Spring_SecurityH2免认证访问控制台配置修改时间:2026-06-17 16:18:40