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

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

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에 정상적으로 접근할 수 있습니다. 🚀

'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
'IT 기술/Spring boot' 카테고리의 다른 글
  • Controller에서 Request Body를 읽지 못하는 문제 해결 - Interceptor를 통한 RequestBody 로그 시도인 경우
  • Spring vs Spring Boot: 차이점과 선택 기준
  • Connection Pool과 @Transactional: 효율적인 데이터베이스 관리를 위한 핵심 개념
  • /gradlew bootRun은 어떻게 동작하는가?
시남
시남
개발하는 사람입니다. 하고 싶은 것들 사이에서 매번 선택하는 삶을 살고 있습니다.
  • 시남
    Refactor Life like code.
    시남
  • 전체
    오늘
    어제
    • 분류 전체보기 (22)
      • IT 기술 (10)
        • Spring boot (5)
      • 이야기 (3)
      • 독서 (0)
      • 개발일기 (4)
        • 1D3Q (4)
  • 블로그 메뉴

    • 홈
    • 태그
    • 미디어로그
    • 위치로그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    회고
    h2-console
    1D3Q
    ai 검색
    reverse tunnel
    h2 콘솔
    프롬프트 엔지니어링
    리버스 터널링
    Spring
    contentcachingrequestwrapper
    java
    기획
    gemini
    바이브코딩
    H2DB
    vibe coding
    로켓방정식의 저주
    springboot h2
    개발일지
    Spring Boot
    사이드프로젝트
    1인기획
    bootrun
    root@localhost
    Ai
    1인개발
    코드 하이라이팅
    AWS
    gradle-wrapper
    h2 console
  • 최근 댓글

  • 최근 글

  • hELLO By정상우.v4.10.4 관리
시남
Spring Boot에서 Security 적용 시 H2 Console(/h2-console) 접근 불가 문제 해결 방법
상단으로

티스토리툴바