문제 상황:
Spring Boot 애플리케이션에서 H2 Console을 활성화한 후 http://localhost:8080/h2-console에 접속을 시도했습니다.
하지만 "localhost에서 연결을 거부했습니다"라는 에러가 발생하며 H2 Console에 접속할 수 없었습니다.
이 문제는 개발 초기 단계에서 테스트 데이터베이스를 사용하려고 할 때 자주 발생하는 상황입니다.
해결 방법:
Spring Security 설정 수정 - Spring Security(6.x 이상)
H2 Console에 접근할 수 있도록 Spring Security 설정을 수정했습니다.
최신 Spring Security(6.x 이상)에서는 아래와 같이 설정해야 합니다:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/h2-console/**").permitAll() // H2 콘솔 경로 허용
)
.csrf(csrf -> csrf
.ignoringRequestMatchers("/h2-console/**") // H2 콘솔에 대해 CSRF 비활성화
)
.headers(headers -> headers
.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable) // frameOptions 비활성화
)
.cors(cors -> cors.configurationSource(corsConfigurationSource())); // CORS 설정
return http.build();
}
- requestMatchers("/h2-console/**").permitAll()
- /h2-console/** 경로에 대한 인증을 비활성화하여 자유롭게 접근 가능하게 설정.
- csrf.ignoringRequestMatchers("/h2-console/**")
- H2 Console의 요청에 대해 CSRF 보호를 비활성화.
- frameOptions(frameOptions -> frameOptions.disable())
- H2 Console에서 사용하는 iframe을 허용.
Spring Security 설정 수정 - 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() // H2 콘솔 경로 인증 없이 허용
.anyRequest().authenticated() // 나머지 요청은 인증 필요
.and()
.csrf()
.ignoringAntMatchers("/h2-console/**") // H2 콘솔 경로에 대해 CSRF 비활성화
.and()
.headers()
.frameOptions().disable(); // iframe 허용
}
}
- antMatchers 사용
- antMatchers("/h2-console/**").permitAll()을 통해 /h2-console/** 경로를 인증 없이 접근 가능하도록 설정.
- anyRequest().authenticated()로 나머지 요청은 인증 필요.
- CSRF 비활성화
- csrf().ignoringAntMatchers("/h2-console/**")로 H2 Console 경로에 대해 CSRF 보호를 비활성화.
- iframe 허용
- headers().frameOptions().disable()로 브라우저가 H2 Console에서 사용하는 iframe을 차단하지 않도록 설정.
설정 후 결과 :
그 외 원인과 해결법:
//application.properties
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
5.x이하 버전들 코드 참고한 블로그:
https://radiant515.tistory.com/288
[H2 error] h2 console localhost에서 연결을 거부했습니다.
h2-console로 접속 후 connection을 누르니 제대로 나오지 않고 localhost에서 연결을 거부했다고 나왔다 그래서 SecurityConfig 클래스에서 configure함수의 내용을 위와 같이 변경해주었다 다시 서버 실행 후
radiant515.tistory.com
'Spring' 카테고리의 다른 글
JPA (Java Persistence API)란? (0) | 2024.12.10 |
---|---|
Spring의 7가지 요청 데이터 처리 어노테이션 (0) | 2024.12.07 |
[Spring] Optional의 활용: Repository, Service, 그리고 ResponseEntity의 역할 (0) | 2024.12.06 |
객체 동등성 비교를 간단하게: @EqualsAndHashCode (1) | 2024.12.04 |
JPA에서 @Modifying 사용법과 동작 원리 (0) | 2024.12.03 |