@[toc] Spring Security는 Spring 기반 애플리케이션을 보호하기 위한 완벽한 솔루션을 제공하는 강력하고 고도로 사용자 정의 가능한 보안 프레임워크입니다. Spring Security에서 경로 일치는 특정 리소스에 액세스할 수 있는 요청을 결정하는 권한 제어의 핵심 부분입니다. 이 기사에서는 Spring Security의 경로 일치 전략을 자세히 소개하고 해당 코드 예제를 제공합니다.
이전 버전의 Spring Security에는 많은 경로 일치 메서드가 있었지만 새 버전의 Spring Security에서는 이러한 메서드를 균일하게 캡슐화하고 처리를 위해 requestMatchers 메서드를 호출합니다.
public C requestMatchers(RequestMatcher... requestMatchers) {
Assert.state(!this.anyRequestConfigured, "Can't configure requestMatchers after anyRequest");
return chainRequestMatchers(Arrays.asList(requestMatchers));
}
requestMatchers 메소드는 RequestMatcher 유형의 매개변수를 수신합니다. 이 인터페이스는 HTTP 요청이 지정된 패턴과 일치하는지 확인하는 데 사용되는 도구입니다. 이 인터페이스는 요청 일치 규칙을 정의하는 유연한 방법을 제공하므로 다양한 요청에 대해 다양한 보안 정책을 구현할 수 있습니다.
따라서 Spring Security의 새 버전에서는 서로 다른 경로 일치 하위 체계가 실제로 RequestMatcher의 서로 다른 구현 클래스입니다.
1. AntPathRequestMatcher
AntPathRequestMatcher
요청 URI를 일치시키기 위해 Ant 스타일 경로 패턴을 사용하는 Spring에서 가장 일반적으로 사용되는 요청 일치자 중 하나입니다.
1.1 Ant 스타일 경로 패턴이란 무엇입니까?
Ant 스타일 경로 일치(Ant Path Matching)는 Java 빌드 도구인 Apache Ant에서 시작되는 리소스 위치에 대한 패턴 일치 규칙입니다. Ant에서 이 모드는 파일 시스템의 파일과 디렉터리를 지정하는 데 사용됩니다. 단순성과 유연성으로 인해 Ant 스타일 경로 패턴은 Spring Security를 포함한 다른 많은 프레임워크 및 애플리케이션에서도 채택됩니다.
Ant 스타일 경로 패턴은 일부 특수 문자를 사용하여 다양한 수준의 경로 일치를 나타냅니다.
-
?
: 모든 단일 문자와 일치합니다(경로 구분 기호 제외). -
*
: 빈 문자열을 제외한 모든 문자(경로 구분 기호 제외)의 시퀀스와 일치합니다. -
**
: 빈 문자열을 포함하여 모든 문자 시퀀스와 일치합니다. 하나 이상의 문자 시퀀스와 일치하며 경로 구분 기호에 걸쳐 있을 수 있습니다. -
{}
: 쉼표로 구분된 여러 패턴과 일치할 수 있는 와일드카드 선택을 나타냅니다. 예를 들어{,春夏秋冬}
봄, 여름, 가을 또는 겨울로 시작하는 모든 문자열을 일치시킬 수 있습니다. -
[]
: 일부 구현에서는 괄호 안의 단일 문자를 일치시키는 데 사용할 수 있습니다. -
()
: 일부 구현에서는 그룹 일치에 사용될 수 있습니다.
Spring Security에서는 URL 경로와 보안 구성 간의 매핑을 정의하기 위해 Ant 스타일 경로 패턴이 자주 사용됩니다. 예를 들어 Ant 스타일 경로 패턴을 사용하여 특정 권한이나 역할이 필요한 URL 경로를 지정할 수 있습니다.
다음은 Ant 스타일 경로 패턴의 몇 가지 예입니다.
-
/users/*
: 또는/users/
와 같이 로 시작하는 모든 경로 와 일치합니다 ./users/123
/users/profile
-
/users/**
: 또는/users/
같은 하위 경로를 포함하여 로 시작하는 모든 경로와 일치합니다 ./users/123
/users/profile/picture
-
/users/123
: 정확히 일치/users/123
. -
/users/{id}
: Ant 스타일 패턴은 아니지만 와 일치할 수 있는 경로 매개변수 일치를 보여줍니다/users/123
./users/456
-
/files/**.{jpg,png}
: or 와 같이 or 로 끝나는/files/
모든 파일 경로 와 일치합니다 ..jpg
.png
/files/image1.jpg
/files/folder/image.png
Ant 스타일 경로 패턴을 사용하면 다양한 보안 요구 사항에 맞게 복잡한 URL 일치 규칙을 유연하게 정의할 수 있습니다.
1.2 기본 사용법
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
// 创建 AntPathRequestMatcher 实例
RequestMatcher antMatcher = new AntPathRequestMatcher("/users/**", "GET");
// 使用 matcher 进行匹配
boolean isMatch = antMatcher.matches(request);
1.3 와일드카드
?
단일 문자와 일치합니다.*
모든 문자 시퀀스와 일치합니다(디렉터리 구분 기호는 제외).**
디렉터리 구분 기호를 포함하여 모든 문자 시퀀스와 일치합니다.
// 匹配 /admin 下的任何资源,包括子目录
RequestMatcher adminMatcher = new AntPathRequestMatcher("/admin/**");
// 匹配 /files 目录下的任何 HTML 文件
RequestMatcher fileMatcher = new AntPathRequestMatcher("/files/*.{html,htm}", "GET");
2. RegexRequestMatcher
RegexRequestMatcher
정규식을 사용하여 요청된 URI 및 HTTP 메서드를 일치시킵니다.
2.1 기본 사용법
import org.springframework.security.web.util.matcher.RegexRequestMatcher;
// 创建 RegexRequestMatcher 实例
RequestMatcher regexMatcher = new RegexRequestMatcher("^/api/.*", "GET");
// 使用 matcher 进行匹配
boolean isMatch = regexMatcher.matches(request);
2.2 정규식 사용
// 匹配任何以 /api 开头的 URI
RequestMatcher apiMatcher = new RegexRequestMatcher("^/api/.*");
// 匹配任何 HTTP 方法
RequestMatcher anyMethodMatcher = new RegexRequestMatcher("^/.*", "GET|POST|PUT|DELETE");
2.3 스프링 시큐리티와 결합
다음 코드는 html, css 및 js로 끝나는 모든 요청을 가로챕니다. 이러한 요청은 직접 액세스할 수 있습니다.
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(a -> a.requestMatchers(new RegexRequestMatcher("^.*\\.(htm|css|js)$","GET")).permitAll())
.formLogin(Customizer.withDefaults())
.csrf(c -> c.disable());
return http.build();
}
}
3. RequestHeaderRequestMatcher
RequestHeaderRequestMatcher
요청 헤더의 키와 값을 일치시키는 데 사용됩니다.
import org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher;
// 创建 RequestHeaderRequestMatcher 实例
RequestMatcher headerMatcher = new RequestHeaderRequestMatcher("User-Agent", "Mozilla.*");
// 使用 matcher 进行匹配
boolean isMatch = headerMatcher.matches(request);
특히 Spring Security에서 사용법은 다음과 같습니다.
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(a -> a.requestMatchers(new RequestHeaderRequestMatcher("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36")).permitAll())
.formLogin(Customizer.withDefaults())
.csrf(c -> c.disable());
return http.build();
}
}
4. NegatedRequestMatcher
NegatedRequestMatcher
기존 RequestMatcher
일치를 무효화할 수 있습니다.
import org.springframework.security.web.util.matcher.NegatedRequestMatcher;
// 创建一个 matcher,然后否定它的匹配结果
RequestMatcher notAdminMatcher = new NegatedRequestMatcher(adminMatcher);
// 使用 negated matcher 进行匹配
boolean isNotMatch = notAdminMatcher.matches(request);
예를 들어, 다음 코드는 를 /hello
제외한 모든 주소에 직접 액세스할 수 있음을 나타냅니다.
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(a -> a.requestMatchers(new NegatedRequestMatcher(new AntPathRequestMatcher("/hello"))).permitAll())
.formLogin(Customizer.withDefaults())
.csrf(c -> c.disable());
return http.build();
}
}
5. AndRequestMatcher 와 OrRequestMatcher
AndRequestMatcher
"AND" 또는 "OR"의 논리적 일치를 수행하기 위해 OrRequestMatcher
여러 인스턴스를 결합하는 데 각각 사용됩니다 .RequestMatcher
5.1 AndRequestMatcher
import org.springframework.security.web.util.matcher.AndRequestMatcher;
// 组合多个 matcher 进行“与”匹配
RequestMatcher andMatcher = new AndRequestMatcher(apiMatcher, headerMatcher);
// 使用 andMatcher 进行匹配
boolean isMatch = andMatcher.matches(request);
5.2 OrRequestMatcher
import org.springframework.security.web.util.matcher.OrRequestMatcher;
// 组合多个 matcher 进行“或”匹配
RequestMatcher orMatcher = new OrRequestMatcher(adminMatcher, fileMatcher);
// 使用 orMatcher 进行匹配
boolean isMatch = orMatcher.matches(request);
6. 요약
Spring은 다양한 요청 일치 요구 사항을 충족하기 위해 다양한 RequestMatcher
구현 클래스를 제공합니다. 이러한 매처를 적절하게 사용하면 보안 정책을 유연하게 정의하고 구현할 수 있습니다. 실제 애플리케이션에서는 비즈니스 요구 사항에 따라 적절한 매처를 선택하고 이를 Spring Security 구성과 결합하여 세분화된 액세스 제어를 구현해야 할 수도 있습니다.