본문 바로가기

Server/Spring

[우당탕탕 개발 일지] Spring Security 트러블 슈팅: AntPathRequestMatcher

반응형
SMALL

Error Log

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'filterChain' defined in class path resource [com/example/userservice/security/WebSecurity.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=[/]}.

 

기존 코드

@Bean
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
	return http
		.csrf(CsrfConfigurer::disable)
		.headers(header -> header.frameOptions(FrameOptionsConfig::disable))
		.authorizeHttpRequests(authorizeRequests ->
			authorizeRequests
				.requestMatchers("/users/**").permitAll()
				.requestMatchers("/**").permitAll()
				.requestMatchers(toH2Console()).permitAll()
				.requestMatchers(new IpAddressMatcher("127.0.0.1")).permitAll()
		)
		.addFilter(getAuthenticationFilter())
		.build();
}

 

Spring Security는 정말 어렵다.. 🥹

에러 로그를 GPT에게 물어보며 살펴보니 경로 문제 같았고,

그 문제는 Spring Security가 최신 버전으로 마이그레이션 되면서 requestMatcher에 이제는 String 타입이 아닌 AntPathRequestMatcher로 넣어줘야 했던 것이었다. 😳

 

변경 코드

@Bean
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
	return http
		.csrf(CsrfConfigurer::disable)
		.headers(header -> header.frameOptions(FrameOptionsConfig::disable))
		.authorizeHttpRequests(authorizeRequests ->
			authorizeRequests
				.requestMatchers(new AntPathRequestMatcher("/users/**")).permitAll()
				.requestMatchers(new AntPathRequestMatcher("/**")).permitAll()
				.requestMatchers(new AntPathRequestMatcher(toH2Console() + "/**")).permitAll()
				.requestMatchers(new IpAddressMatcher("127.0.0.1")).permitAll()
		)
		.addFilter(getAuthenticationFilter())
		.build();
}

 

이렇게 new AntPathRequestMatcher로 감싸주고 실행시키면 잘 실행된다 👍

반응형
LIST