새소식

반응형
Java/Spring

Spring Security RequestMatcher Interface

  • -
반응형

RequestMatchers

Spring Security 에서 요청을 필터링하거나 특정 요청에 대한 보안 정책(인가, 인증 등) 을 매칭할 때 사용하는

핵심 인터페이스 중 하나이다.

👉 org.springframework.security.web.util.matcher.RequestMatcher

 

🔍 RequestMatcher 개요

RequestMatcher  는 HTTP 요청(HttpServletRequest) 이 특정 조건과 일치하는지 여부를 판단하기 위한

전략(Strategy) 인터페이스다.

public interface RequestMatcher {
    boolean matches(HttpServletRequest request);
}

 

  • 들어온 요청이 "이 URL, 이 메서드, 이 헤더 조건에 맞는가?" 를 판별하는 역할이다.
  • true/false 결과를 반환해서, SecurityFilterChain 이나 AccessDecisionManager 등에서 다음 처리 여부를 결정한다.

 

🧩 주요 구현체들

Spring Security 는 여러가지 RequestMatcher 구현체를 기본 제공한다.

구현체 설명
AntPathRequestMatcher /api/**, /user/* 같은 Ant 스타일 패턴으로 매칭
RegexRequestMatcher 정규식 기반으로 요청 매칭
MvcRequestMatcher Spring MVC의 HandlerMapping 패턴(/{id}, /** 등)을 기반으로 매칭
OrRequestMatcher, AndRequestMatcher 여러 matcher를 조합 (OR / AND 논리)
NegatedRequestMatcher 주어진 matcher의 반대 결과

 

⚙️ 실전 예시

1️⃣ Security 설정에서 URL 매칭

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/public/**").permitAll()
            .requestMatchers("/admin/**").hasRole("ADMIN")
            .anyRequest().authenticated()
        );
    return http.build();
}

 

여기서 .requestMatchers("/public/**") 내부적으로는

👉 AntPathRequestMatcher("/public/**")를 생성해서 RequestMatcher로 등록됩니다.

 

2️⃣ 직접 커스텀 필터에서 사용

예를 들어 특정 경로만 필터가 작동하도록 할 수 있다.

public class CustomFilter extends OncePerRequestFilter {

    private final RequestMatcher requestMatcher = new AntPathRequestMatcher("/api/**");

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        if (requestMatcher.matches(request)) {
            // /api/** 경로일 때만 필터 로직 수행
            System.out.println("API 요청 감지!");
        }

        chain.doFilter(request, response);
    }
}

 

 

✅ 요약

항목 설명
인터페이스 이름 RequestMatcher
역할 특정 요청(HttpServletRequest)이 조건에 맞는지 판별
사용 위치 SecurityFilterChain, Custom Filter, AccessDecision 등
주요 구현체 AntPathRequestMatcher, RegexRequestMatcher, MvcRequestMatcher 등
내부 사용 예 .requestMatchers() 메서드에서 자동으로 활용됨

 

 

반응형
Contents