Skip to content

Commit 6ab0e75

Browse files
committed
Add PathPatternRequestMatcher
Closes gh-16429
1 parent 174f17e commit 6ab0e75

File tree

3 files changed

+342
-0
lines changed

3 files changed

+342
-0
lines changed
Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
/*
2+
* Copyright 2002-2025 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.security.web.servlet.util.matcher;
18+
19+
import java.util.Objects;
20+
21+
import jakarta.servlet.http.HttpServletRequest;
22+
23+
import org.springframework.http.HttpMethod;
24+
import org.springframework.http.server.PathContainer;
25+
import org.springframework.http.server.RequestPath;
26+
import org.springframework.security.web.util.matcher.RequestMatcher;
27+
import org.springframework.util.Assert;
28+
import org.springframework.web.util.WebUtils;
29+
import org.springframework.web.util.pattern.PathPattern;
30+
import org.springframework.web.util.pattern.PathPatternParser;
31+
32+
/**
33+
* A {@link RequestMatcher} that uses {@link PathPattern}s to match against each
34+
* {@link HttpServletRequest}. Specifically, this means that the class anticipates that
35+
* the provided pattern does not include the servlet path in order to align with Spring
36+
* MVC.
37+
*
38+
* <p>
39+
* Note that the {@link org.springframework.web.servlet.HandlerMapping} that contains the
40+
* related URI patterns must be using the same
41+
* {@link org.springframework.web.util.pattern.PathPatternParser} configured in this
42+
* class.
43+
* </p>
44+
*
45+
* @author Josh Cummings
46+
* @since 6.5
47+
*/
48+
public final class PathPatternRequestMatcher implements RequestMatcher {
49+
50+
private final HttpMethod method;
51+
52+
private final PathPattern pattern;
53+
54+
/**
55+
* Creates an {@link PathPatternRequestMatcher} that uses the provided
56+
* {@code pattern}.
57+
* <p>
58+
* The {@code pattern} should be absolute (less the context path)
59+
* </p>
60+
* @param pattern the pattern used to match
61+
*/
62+
public PathPatternRequestMatcher(PathPattern pattern) {
63+
this(null, pattern);
64+
}
65+
66+
/**
67+
* Creates an {@link PathPatternRequestMatcher} that uses the provided {@code pattern}
68+
* and HTTP {@code method} to match.
69+
* <p>
70+
* The {@code pattern} should be absolute (less the context path)
71+
* </p>
72+
* @param method the {@link HttpMethod}, can be null
73+
* @param pattern the pattern used to match; if a path, must be relative to its
74+
* servlet path
75+
*/
76+
public PathPatternRequestMatcher(HttpMethod method, PathPattern pattern) {
77+
this.method = method;
78+
this.pattern = pattern;
79+
}
80+
81+
/**
82+
* Creates an {@link PathPatternRequestMatcher} that uses the provided {@code pattern}
83+
* and HTTP {@code method} to match.
84+
* <p>
85+
* The {@code pattern} should be absolute (less the context path)
86+
* </p>
87+
* @param method the {@link HttpMethod}, can be null
88+
* @param pattern the pattern used to match; if a path, must be relative to its
89+
* servlet path
90+
* @return the generated {@link PathPatternRequestMatcher}
91+
*/
92+
public static PathPatternRequestMatcher pathPattern(HttpMethod method, String pattern) {
93+
Assert.notNull(pattern, "pattern cannot be null");
94+
Assert.isTrue(pattern.startsWith("/"), "pattern must start with '/'");
95+
PathPatternParser parser = PathPatternParser.defaultInstance;
96+
String parsed = parser.initFullPathPattern(pattern);
97+
PathPattern pathPattern = parser.parse(parsed);
98+
return new PathPatternRequestMatcher(method, pathPattern);
99+
}
100+
101+
/**
102+
* Creates an {@link PathPatternRequestMatcher} that uses the provided
103+
* {@code pattern}.
104+
* <p>
105+
* The {@code pattern} should be absolute (less the context path)
106+
* </p>
107+
* @param pattern the pattern used to match
108+
* @return the generated {@link PathPatternRequestMatcher}
109+
*/
110+
public static PathPatternRequestMatcher pathPattern(String pattern) {
111+
return pathPattern(null, pattern);
112+
}
113+
114+
/**
115+
* {@inheritDoc}
116+
*/
117+
@Override
118+
public boolean matches(HttpServletRequest request) {
119+
return matcher(request).isMatch();
120+
}
121+
122+
/**
123+
* {@inheritDoc}
124+
*/
125+
@Override
126+
public MatchResult matcher(HttpServletRequest request) {
127+
if (this.method != null && !this.method.name().equals(request.getMethod())) {
128+
return MatchResult.notMatch();
129+
}
130+
PathContainer path = getRequestPath(request).pathWithinApplication();
131+
PathPattern.PathMatchInfo info = this.pattern.matchAndExtract(path);
132+
return (info != null) ? MatchResult.match(info.getUriVariables()) : MatchResult.notMatch();
133+
}
134+
135+
private RequestPath getRequestPath(HttpServletRequest request) {
136+
String requestUri = (String) request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE);
137+
requestUri = (requestUri != null) ? requestUri : request.getRequestURI();
138+
return RequestPath.parse(requestUri, request.getContextPath());
139+
}
140+
141+
/**
142+
* {@inheritDoc}
143+
*/
144+
@Override
145+
public boolean equals(Object o) {
146+
if (!(o instanceof PathPatternRequestMatcher that)) {
147+
return false;
148+
}
149+
return Objects.equals(this.method, that.method) && Objects.equals(this.pattern, that.pattern);
150+
}
151+
152+
/**
153+
* {@inheritDoc}
154+
*/
155+
@Override
156+
public int hashCode() {
157+
return Objects.hash(this.method, this.pattern);
158+
}
159+
160+
/**
161+
* {@inheritDoc}
162+
*/
163+
@Override
164+
public String toString() {
165+
return "PathPatternRequestMatcher [method=" + this.method + ", pattern=" + this.pattern + "]";
166+
}
167+
168+
}
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/*
2+
* Copyright 2002-2025 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.security.web.util.matcher;
18+
19+
import java.util.ArrayList;
20+
import java.util.List;
21+
22+
import org.springframework.http.HttpMethod;
23+
24+
/**
25+
* An interface that creates {@link RequestMatcher} instances in different ways
26+
*
27+
* @author Josh Cummings
28+
* @since 6.5
29+
*/
30+
public interface RequestMatcherBuilder {
31+
32+
/**
33+
* Create an array of {@link RequestMatcher}s that matches this method and each
34+
* respective pattern.
35+
* <p>
36+
* {@code pattern}s should start with a slash
37+
* </p>
38+
* @param method the HTTP method to match
39+
* @param patterns the separate set of patterns to match
40+
* @return one {@link RequestMatcher} per pattern
41+
*/
42+
default RequestMatcher[] pattern(HttpMethod method, String... patterns) {
43+
List<RequestMatcher> requestMatchers = new ArrayList<>();
44+
for (String pattern : patterns) {
45+
requestMatchers.add(pattern(method, pattern));
46+
}
47+
return requestMatchers.toArray(RequestMatcher[]::new);
48+
}
49+
50+
/**
51+
* Create an array of {@link RequestMatcher}s that matches each respective pattern
52+
* regardless of the HTTP method
53+
* <p>
54+
* {@code pattern}s should start with a slash
55+
* </p>
56+
* @param patterns the separate set of patterns to match
57+
* @return one {@link RequestMatcher} per pattern
58+
*/
59+
default RequestMatcher[] pattern(String... patterns) {
60+
return pattern(null, patterns);
61+
}
62+
63+
/**
64+
* Create a {@link RequestMatcher}s that matches the given pattern
65+
* <p>
66+
* {@code pattern} should start with a slash
67+
* </p>
68+
* @param pattern the pattern to match
69+
* @return a {@link RequestMatcher} that matches this pattern
70+
*/
71+
default RequestMatcher pattern(String pattern) {
72+
return pattern(null, pattern);
73+
}
74+
75+
/**
76+
* Create a {@link RequestMatcher}s that matches any request
77+
* @return a {@link RequestMatcher} that matches any request
78+
*/
79+
default RequestMatcher anyRequest() {
80+
return pattern(null, "/**");
81+
}
82+
83+
RequestMatcher pattern(HttpMethod method, String pattern);
84+
85+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
/*
2+
* Copyright 2002-2025 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.security.web.servlet.util.matcher;
18+
19+
import org.junit.jupiter.api.Test;
20+
21+
import org.springframework.http.HttpMethod;
22+
import org.springframework.mock.web.MockHttpServletRequest;
23+
import org.springframework.security.web.util.matcher.RequestMatcher;
24+
import org.springframework.web.util.ServletRequestPathUtils;
25+
26+
import static org.assertj.core.api.Assertions.assertThat;
27+
28+
/**
29+
* Tests for {@link PathPatternRequestMatcher}
30+
*/
31+
public class PathPatternRequestMatcherTests {
32+
33+
@Test
34+
void matcherWhenPatternMatchesRequestThenMatchResult() {
35+
RequestMatcher matcher = PathPatternRequestMatcher.pathPattern("/uri");
36+
assertThat(matcher.matches(request("/uri"))).isTrue();
37+
}
38+
39+
@Test
40+
void matcherWhenPatternContainsPlaceholdersThenMatchResult() {
41+
RequestMatcher matcher = PathPatternRequestMatcher.pathPattern("/uri/{username}");
42+
assertThat(matcher.matcher(request("/uri/bob")).getVariables()).containsEntry("username", "bob");
43+
}
44+
45+
@Test
46+
void matcherWhenOnlyPathInfoMatchesThenNoMatch() {
47+
RequestMatcher matcher = PathPatternRequestMatcher.pathPattern("/uri");
48+
assertThat(matcher.matches(request("GET", "/mvc/uri", "/mvc"))).isFalse();
49+
}
50+
51+
@Test
52+
void matcherWhenSameMethodThenMatchResult() {
53+
RequestMatcher matcher = PathPatternRequestMatcher.pathPattern(HttpMethod.GET, "/uri");
54+
assertThat(matcher.matches(request("/uri"))).isTrue();
55+
}
56+
57+
@Test
58+
void matcherWhenDifferentPathThenNoMatch() {
59+
RequestMatcher matcher = PathPatternRequestMatcher.pathPattern(HttpMethod.GET, "/uri");
60+
assertThat(matcher.matches(request("GET", "/urj", ""))).isFalse();
61+
}
62+
63+
@Test
64+
void matcherWhenDifferentMethodThenNoMatch() {
65+
RequestMatcher matcher = PathPatternRequestMatcher.pathPattern(HttpMethod.GET, "/uri");
66+
assertThat(matcher.matches(request("POST", "/mvc/uri", "/mvc"))).isFalse();
67+
}
68+
69+
@Test
70+
void matcherWhenNoMethodThenMatches() {
71+
RequestMatcher matcher = PathPatternRequestMatcher.pathPattern("/uri");
72+
assertThat(matcher.matches(request("POST", "/uri", ""))).isTrue();
73+
assertThat(matcher.matches(request("GET", "/uri", ""))).isTrue();
74+
}
75+
76+
MockHttpServletRequest request(String uri) {
77+
MockHttpServletRequest request = new MockHttpServletRequest("GET", uri);
78+
ServletRequestPathUtils.parseAndCache(request);
79+
return request;
80+
}
81+
82+
MockHttpServletRequest request(String method, String uri, String servletPath) {
83+
MockHttpServletRequest request = new MockHttpServletRequest(method, uri);
84+
request.setServletPath(servletPath);
85+
ServletRequestPathUtils.parseAndCache(request);
86+
return request;
87+
}
88+
89+
}

0 commit comments

Comments
 (0)