spring

[Spring Security] h2-console가 Spring Security 필터를 통과하지 않게 하는 방법(제일 쉬운 방법)_error is h2 console localhost에서 연결을 거부했습니다.

seulhasony 2024. 1. 13. 11:43

h2-console이 필터를 통과하지 않게 하기 위해 해야하는 설정에 대해 application.yml 설정과 웹 ignoring() 방법에 대해서 정리하겠습니다.

 

별다른 설정없이 h2-console 창을 열려고 하면 로그인화면으로 바로 넘어 갑니다.

그럼 개발할 때 번거로움이 발생하겠지요! 개발환경에서는 h2-console이 필터를 통과하지 않도록 설정하겠습니다.

혹은 아래와 같은 이미지가 뜬다면 제가 설정한 것들을 한 번 적용해보세요! 도움이 되길 바랍니다,,

오류 발생!

 

application.yml

spring:
  h2:
    console:
      enabled: true
      path: /h2-console
  datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:~/szs_challenges;MODE=MySQL
    username: sa

 

설정파일에서 필터를 통과하지 않는 코드를 작성하지는 않지만 혹시나 설정파일도 궁금해 하실까봐 같이 올려 드립니다.

path는 검색창에서 localhost:8080/h2-console로 작용됩니다.

url은 따로 설정을 하시지 않으시면 자동으로 생성되기 때문에 저는 번거로워서 직접 설정했습니다.

 

SecurityConfiguration.java

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    @Bean
    @ConditionalOnProperty(name = "spring.h2.console.enabled",havingValue = "true")
    public WebSecurityCustomizer configureH2ConsoleEnable(){
        return web -> web.ignoring()
                .requestMatchers(PathRequest.toH2Console());
    }
 }

 

코드를 설명하자면, @ConditionalOnProperty 어노테이션을 사용해 설정파일 즉 application.yml에서 enbled가 true로 되어있는 경우 h2-console은 필터에 통과되지 않는 아래의 메소드를 탄다! 이런 의미입니다.

 

그럼 개발환경에서 true로 설정하고 로컬에서는 false로 설정만 바꾸면 h2-console도 필요에 따라 필터를 통과할 수 있게 됩니다! 크으

 

모쪼록 다들 즐거운 개발하세요!