IT 기술/Spring boot / / 2025. 3. 5. 15:40

Spring Boot에서 Security 적용 시 H2 Console(/h2-console) 접근 불가 문제 해결 방법

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 정상 작동 확인)

  1. SecurityConfig에서 /h2-console/**에 대한 접근을 허용했는지 확인
  2. CSRF 보호를 H2 Console에 대해서만 비활성화했는지 확인
  3. application.properties에서 H2 Console이 활성화되어 있는지 확인
  4. 서버를 재시작한 후 /h2-console에 접근하여 정상적으로 동작하는지 테스트

이제 Spring Boot + Spring Security 환경에서도 H2 Console에 정상적으로 접근할 수 있습니다. 🚀

  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유