Spring Boot 환경에서 Spring Security 설정을 활성화한 상태에서 In-memory H2 Database를 사용할 경우, /h2-console
에 접근이 차단되는 문제가 발생할 수 있습니다. 이는 기본적으로 Spring Security가 모든 요청을 보호하기 때문입니다. 이번 포스팅에서는 Spring Boot 2.x 및 3.x 버전에서 H2 Console 접근 문제를 해결하는 방법을 설명합니다.
🔍 Spring Boot H2 Console 접근 불가 원인
Spring Boot 2.x 이상에서는 Spring Security가 자동으로 활성화되며, 기본적으로 모든 경로에 대한 인증을 요구합니다. 또한, H2 Console(/h2-console
)은 프레임을 사용하여 UI를 제공하는데, Spring Security의 X-Frame-Options 설정이 이를 차단하기도 합니다.
🛠 Spring Boot H2 Console 접근 문제 해결 방법
1️⃣ Spring Security 설정에서 H2 Console 허용
Spring Security 설정 파일을 수정하여 /h2-console/**
에 대한 접근을 허용해야 합니다.
✅ Spring Boot 3.x (Spring Security 6.x) 버전 설정 (Lambda 방식)
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/h2-console/**").permitAll()
.anyRequest().authenticated()
)
.csrf(csrf -> csrf
.ignoringRequestMatchers("/h2-console/**")
)
.headers(headers -> headers
.frameOptions(frame -> frame.sameOrigin())
)
.formLogin(withDefaults());
return http.build();
}
}
설명
/h2-console/**
경로에 대해permitAll()
적용 → 인증 없이 접근 가능- CSRF 보호 비활성화 →
ignoringRequestMatchers("/h2-console/**")
frameOptions().sameOrigin()
설정 → 프레임을 통한 접근 허용
✅ Spring Boot 2.x (Spring Security 5.x) 버전 설정
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/h2-console/**").permitAll()
.anyRequest().authenticated()
.and()
.csrf().ignoringAntMatchers("/h2-console/**")
.and()
.headers().frameOptions().sameOrigin()
.and()
.formLogin();
}
}
Spring Boot 2.x 버전에서는 WebSecurityConfigurerAdapter를 상속하여 보안 설정을 정의합니다.
2️⃣ Spring Boot H2 Console 설정 변경 (application.properties
/ application.yml
)
✅ H2 Console 활성화 설정
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring:
h2:
console:
enabled: true
path: /h2-console
✅ H2 Database 설정 (임베디드 모드 사용 시)
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.hikari.maximum-pool-size=5
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
jdbc:h2:mem:testdb → 메모리 모드에서 동작하도록 설정
✅ 최종 점검 사항 (Spring Boot + Security 환경에서 H2 Console 정상 작동 확인)
SecurityConfig
에서/h2-console/**
에 대한 접근을 허용했는지 확인- CSRF 보호를 H2 Console에 대해서만 비활성화했는지 확인
application.properties
에서 H2 Console이 활성화되어 있는지 확인- 서버를 재시작한 후
/h2-console
에 접근하여 정상적으로 동작하는지 테스트
이제 Spring Boot + Spring Security 환경에서도 H2 Console에 정상적으로 접근할 수 있습니다. 🚀
'IT 기술 > Spring boot' 카테고리의 다른 글
Controller에서 Request Body를 읽지 못하는 문제 해결 - Interceptor를 통한 RequestBody 로그 시도인 경우 (0) | 2025.04.06 |
---|---|
Spring vs Spring Boot: 차이점과 선택 기준 (1) | 2025.03.18 |
Connection Pool과 @Transactional: 효율적인 데이터베이스 관리를 위한 핵심 개념 (0) | 2025.02.25 |
/gradlew bootRun은 어떻게 동작하는가? (1) | 2025.02.22 |