Spring Security 환경에서 h2 console enabled : true일 때 오류

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Unsatisfied dependency expressed through method 'setFilterChains' parameter 0: Error creating bean with name 'filterChain' defined in class path resource [com/example/securityspring/config/SecurityConfig.class]: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'filterChain' threw exception with message: This method cannot decide whether these patterns are Spring MVC patterns or not. If this endpoint is a Spring MVC endpoint, please use requestMatchers(MvcRequestMatcher); otherwise, please use requestMatchers(AntPathRequestMatcher).

This is because there is more than one mappable servlet in your servlet context: {org.h2.server.web.JakartaWebServlet=[/h2-console/*], org.springframework.web.servlet.DispatcherServlet=[/]}.

For each MvcRequestMatcher, call MvcRequestMatcher#setServletPath to indicate the servlet path.

 

위와 같은 오류 발생 문제의 원인은 h2 데이터베이스의 console 사용을 아래와 같이 허용해주었는데 h2 console 사용 시 서블릿 컨텍스트에 h2-console과 dispatcherServlet의 두 가지 서블릿이 매핑되어 어떤 서블릿을 사용해야하는지 알 수 없어 발생하는 오류

 

application.yml

spring:

  h2:
    console:
      enabled: true

 

filterChain의 requestMatchers에 MvcRequestMatcher, AntPathRequestMatcher 중 사용하려는 클래스를 명확하게 지정해줘야한다. 

 

@Bean
public SecurityFilterChain filterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception {
	http.authorizeHttpRequests((authz) -> authz
    		.requestMatchers(new MvcRequestMatcher(introspector,"/api/hello")).permitAll()
		.anyRequest().authenticated())
		.httpBasic(Customizer.withDefaults());
	return http.build();
}

 

오류만 제대로 읽었어도 금방 찾을 수 있는 에러였다.

반응형