Skip to content

Commit 918a0a9

Browse files
committed
Add PathPatternRequestMatcher
Closes spring-projectsgh-16429
1 parent 7b8ff72 commit 918a0a9

File tree

3 files changed

+345
-0
lines changed

3 files changed

+345
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
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.security.web.util.matcher.RequestMatcherBuilder;
28+
import org.springframework.util.Assert;
29+
import org.springframework.web.util.WebUtils;
30+
import org.springframework.web.util.pattern.PathPattern;
31+
import org.springframework.web.util.pattern.PathPatternParser;
32+
33+
/**
34+
* A {@link RequestMatcher} that uses {@link PathPattern}s to match against each
35+
* {@link HttpServletRequest}. Specifically, this means that the class anticipates that
36+
* the provided pattern does not include the servlet path in order to align with Spring
37+
* MVC.
38+
*
39+
* <p>
40+
* Note that the {@link org.springframework.web.servlet.HandlerMapping} that contains the
41+
* related URI patterns must be using the same
42+
* {@link org.springframework.web.util.pattern.PathPatternParser} configured in this
43+
* class.
44+
* </p>
45+
*
46+
* @author Josh Cummings
47+
* @since 6.5
48+
*/
49+
public final class PathPatternRequestMatcher implements RequestMatcher {
50+
51+
private HttpMethod method;
52+
53+
private final PathPattern pattern;
54+
55+
PathPatternRequestMatcher(PathPattern pattern) {
56+
this.pattern = pattern;
57+
}
58+
59+
/**
60+
* Create a {@link Builder} for creating {@link PathPattern}-based request matchers.
61+
* That is, matchers that anticipate patterns do not specify the servlet path.
62+
* @return the {@link Builder}
63+
*/
64+
public static Builder builder() {
65+
return new Builder(PathPatternParser.defaultInstance);
66+
}
67+
68+
/**
69+
* Create a {@link Builder} for creating {@link PathPattern}-based request matchers.
70+
* That is, matchers that anticipate patterns do not specify the servlet path.
71+
* @param parser the {@link PathPatternParser}; only needed when different from
72+
* {@link PathPatternParser#defaultInstance}
73+
* @return the {@link Builder}
74+
*/
75+
public static Builder withPathPatternParser(PathPatternParser parser) {
76+
return new Builder(parser);
77+
}
78+
79+
/**
80+
* {@inheritDoc}
81+
*/
82+
@Override
83+
public boolean matches(HttpServletRequest request) {
84+
return matcher(request).isMatch();
85+
}
86+
87+
/**
88+
* {@inheritDoc}
89+
*/
90+
@Override
91+
public MatchResult matcher(HttpServletRequest request) {
92+
if (this.method != null && !this.method.name().equals(request.getMethod())) {
93+
return MatchResult.notMatch();
94+
}
95+
PathContainer path = getRequestPath(request).pathWithinApplication();
96+
PathPattern.PathMatchInfo info = this.pattern.matchAndExtract(path);
97+
return (info != null) ? MatchResult.match(info.getUriVariables()) : MatchResult.notMatch();
98+
}
99+
100+
void setMethod(HttpMethod method) {
101+
this.method = method;
102+
}
103+
104+
private RequestPath getRequestPath(HttpServletRequest request) {
105+
String requestUri = (String) request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE);
106+
requestUri = (requestUri != null) ? requestUri : request.getRequestURI();
107+
return RequestPath.parse(requestUri, request.getContextPath());
108+
}
109+
110+
/**
111+
* {@inheritDoc}
112+
*/
113+
@Override
114+
public boolean equals(Object o) {
115+
if (!(o instanceof PathPatternRequestMatcher that)) {
116+
return false;
117+
}
118+
return Objects.equals(this.method, that.method) && Objects.equals(this.pattern, that.pattern);
119+
}
120+
121+
/**
122+
* {@inheritDoc}
123+
*/
124+
@Override
125+
public int hashCode() {
126+
return Objects.hash(this.method, this.pattern);
127+
}
128+
129+
/**
130+
* {@inheritDoc}
131+
*/
132+
@Override
133+
public String toString() {
134+
return "PathPatternRequestMatcher [method=" + this.method + ", pattern=" + this.pattern + "]";
135+
}
136+
137+
/**
138+
* A builder for {@link PathPatternRequestMatcher}
139+
*
140+
* @author Marcus Da Coregio
141+
* @since 6.5
142+
*/
143+
public static final class Builder implements RequestMatcherBuilder {
144+
145+
private final PathPatternParser parser;
146+
147+
/**
148+
* Construct a new instance of this builder
149+
*/
150+
public Builder(PathPatternParser parser) {
151+
Assert.notNull(parser, "pathPatternParser cannot be null");
152+
this.parser = parser;
153+
}
154+
155+
/**
156+
* Creates an {@link PathPatternRequestMatcher} that uses the provided
157+
* {@code pattern} and HTTP {@code method} to match.
158+
* <p>
159+
* If the {@code pattern} is a path, it must be specified relative to its servlet
160+
* path.
161+
* </p>
162+
* @param method the {@link HttpMethod}, can be null
163+
* @param pattern the pattern used to match; if a path, must be relative to its
164+
* servlet path
165+
* @return the generated {@link PathPatternRequestMatcher}
166+
*/
167+
public PathPatternRequestMatcher pattern(HttpMethod method, String pattern) {
168+
String parsed = this.parser.initFullPathPattern(pattern);
169+
PathPattern pathPattern = this.parser.parse(parsed);
170+
PathPatternRequestMatcher requestMatcher = new PathPatternRequestMatcher(pathPattern);
171+
requestMatcher.setMethod(method);
172+
return requestMatcher;
173+
}
174+
175+
}
176+
177+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
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 respective
34+
* pattern.
35+
* <p>{@code pattern}s should start with a slash</p>
36+
* @param method the HTTP method to match
37+
* @param patterns the separate set of patterns to match
38+
* @return one {@link RequestMatcher} per pattern
39+
*/
40+
default RequestMatcher[] pattern(HttpMethod method, String... patterns) {
41+
List<RequestMatcher> requestMatchers = new ArrayList<>();
42+
for (String pattern : patterns) {
43+
requestMatchers.add(pattern(method, pattern));
44+
}
45+
return requestMatchers.toArray(RequestMatcher[]::new);
46+
}
47+
48+
/**
49+
* Create an array of {@link RequestMatcher}s that matches each respective
50+
* pattern regardless of the HTTP method
51+
* <p>{@code pattern}s should start with a slash</p>
52+
* @param patterns the separate set of patterns to match
53+
* @return one {@link RequestMatcher} per pattern
54+
*/
55+
default RequestMatcher[] pattern(String... patterns) {
56+
return pattern(null, patterns);
57+
}
58+
59+
/**
60+
* Create a {@link RequestMatcher}s that matches the given pattern
61+
* <p>{@code pattern} should start with a slash</p>
62+
* @param pattern the pattern to match
63+
* @return a {@link RequestMatcher} that matches this pattern
64+
*/
65+
default RequestMatcher pattern(String pattern) {
66+
return pattern(null, pattern);
67+
}
68+
69+
/**
70+
* Create a {@link RequestMatcher}s that matches any request
71+
* @return a {@link RequestMatcher} that matches any request
72+
*/
73+
default RequestMatcher anyRequest() {
74+
return pattern(null, "/**");
75+
}
76+
77+
RequestMatcher pattern(HttpMethod method, String pattern);
78+
79+
}
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.builder().pattern("/uri");
36+
assertThat(matcher.matches(request("/uri"))).isTrue();
37+
}
38+
39+
@Test
40+
void matcherWhenPatternContainsPlaceholdersThenMatchResult() {
41+
RequestMatcher matcher = PathPatternRequestMatcher.builder().pattern("/uri/{username}");
42+
assertThat(matcher.matcher(request("/uri/bob")).getVariables()).containsEntry("username", "bob");
43+
}
44+
45+
@Test
46+
void matcherWhenOnlyPathInfoMatchesThenNoMatch() {
47+
RequestMatcher matcher = PathPatternRequestMatcher.builder().pattern("/uri");
48+
assertThat(matcher.matches(request("GET", "/mvc/uri", "/mvc"))).isFalse();
49+
}
50+
51+
@Test
52+
void matcherWhenSameMethodThenMatchResult() {
53+
RequestMatcher matcher = PathPatternRequestMatcher.builder().pattern(HttpMethod.GET, "/uri");
54+
assertThat(matcher.matches(request("/uri"))).isTrue();
55+
}
56+
57+
@Test
58+
void matcherWhenDifferentPathThenNoMatch() {
59+
RequestMatcher matcher = PathPatternRequestMatcher.builder().pattern(HttpMethod.GET, "/uri");
60+
assertThat(matcher.matches(request("GET", "/urj", ""))).isFalse();
61+
}
62+
63+
@Test
64+
void matcherWhenDifferentMethodThenNoMatch() {
65+
RequestMatcher matcher = PathPatternRequestMatcher.builder().pattern(HttpMethod.GET, "/uri");
66+
assertThat(matcher.matches(request("POST", "/mvc/uri", "/mvc"))).isFalse();
67+
}
68+
69+
@Test
70+
void matcherWhenNoMethodThenMatches() {
71+
RequestMatcher matcher = PathPatternRequestMatcher.builder().pattern("/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)