본문 바로가기
Web/Spring Boot

Spring Boot Security - please use requestMatchers(MvcRequestMatcher); otherwise, please use requestMatchers(AntPathRequestMatcher) Error 해결 법

by 주남2 2023. 9. 2.
반응형

JWT 를 사용한 로그인, 회원가입 구현 중에 다음과 같은 오류가 발생했다. 

 

에러 코드

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .csrf(csrf -> csrf.disable())
        .authorizeHttpRequests(authorizeHttpRequests -> authorizeHttpRequests
            .requestMatchers("/api/hello", "/api/authenticate", "/api/signup").permitAll()
            .requestMatchers(PathRequest.toH2Console()).permitAll()
            .anyRequest().authenticated()
        )
    return http.build();
}

 

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'securityFilterChain' 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). at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:171) at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:655) ... 24 common frames omitte

 

참고한 블로그에서는 해당 오류가 발생했는데 원인을 찾아보니 최신 버전으로 사용한 스프링 부트와 시큐리티의 버전 차이였다.

 

내가 사용한 버전이다.

Spring Boot : 3.1.3

Java : 17

Spring-Security-Config : 6.1.2

 

에러 문구를 보면 MvcRequestMatcher 인지AntPathRequestMatcher 확실하게 구분이 필요하다고 말한다.

permit all 하는 url 들을 미리 상수로 정의하고,

requestMathchers 에 Stream 방식으로 AntPathRequestMatcher Array 를 만들어서 전달하는 방식으로 해결했다.

 

@RequiredArgsConstructor
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    private static final String[] PERMIT_ALL_URLS = new String[] {
            "/api/hello",
            "/api/authenticate",
            "/api/signup"
    };

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())

            .authorizeHttpRequests(authorHttpRequests -> authorHttpRequests
                    .requestMatchers(Stream
                            .of(PERMIT_ALL_URLS)
                            .map(AntPathRequestMatcher::antMatcher)
                            .toArray(AntPathRequestMatcher[]::new)).permitAll()
                    .requestMatchers(PathRequest.toH2Console()).permitAll()
                    .anyRequest().authenticated()
            );

        return http.build();
    }
}
반응형