Prgress
This commit is contained in:
@@ -34,6 +34,7 @@ import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.core.log.LogMessage;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.context.SecurityContextHolderStrategy;
|
||||
import org.springframework.security.web.access.PathPatternRequestTransformer;
|
||||
import org.springframework.security.web.firewall.FirewalledRequest;
|
||||
import org.springframework.security.web.firewall.HttpFirewall;
|
||||
import org.springframework.security.web.firewall.HttpStatusRequestRejectedHandler;
|
||||
@@ -258,7 +259,9 @@ public class FilterChainProxy extends GenericFilterBean {
|
||||
* @return matching filter list
|
||||
*/
|
||||
public List<Filter> getFilters(String url) {
|
||||
return getFilters(this.firewall.getFirewalledRequest(new FilterInvocation(url, "GET").getRequest()));
|
||||
PathPatternRequestTransformer requestTransformer = new PathPatternRequestTransformer();
|
||||
HttpServletRequest transformed = requestTransformer.transform(new FilterInvocation(url, "GET").getRequest());
|
||||
return getFilters(this.firewall.getFirewalledRequest(transformed));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
-98
@@ -1,98 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.web.access;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import jakarta.servlet.DispatcherType;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletRequestWrapper;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
|
||||
|
||||
/**
|
||||
* Transforms by passing it into
|
||||
* {@link HandlerMappingIntrospector#setCache(HttpServletRequest)}. Before, it wraps the
|
||||
* {@link HttpServletRequest} to ensure that the methods needed work since some methods by
|
||||
* default throw {@link UnsupportedOperationException}.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @deprecated please use {@link PathPatternRequestTransformer} instead
|
||||
*/
|
||||
@Deprecated(forRemoval = true)
|
||||
public class HandlerMappingIntrospectorRequestTransformer
|
||||
implements AuthorizationManagerWebInvocationPrivilegeEvaluator.HttpServletRequestTransformer {
|
||||
|
||||
private final HandlerMappingIntrospector introspector;
|
||||
|
||||
public HandlerMappingIntrospectorRequestTransformer(HandlerMappingIntrospector introspector) {
|
||||
Assert.notNull(introspector, "introspector canot be null");
|
||||
this.introspector = introspector;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpServletRequest transform(HttpServletRequest request) {
|
||||
CacheableRequestWrapper cacheableRequest = new CacheableRequestWrapper(request);
|
||||
this.introspector.setCache(cacheableRequest);
|
||||
return cacheableRequest;
|
||||
}
|
||||
|
||||
static final class CacheableRequestWrapper extends HttpServletRequestWrapper {
|
||||
|
||||
private final Map<String, Object> attributes = new HashMap<>();
|
||||
|
||||
/**
|
||||
* Constructs a request object wrapping the given request.
|
||||
* @param request the {@link HttpServletRequest} to be wrapped.
|
||||
* @throws IllegalArgumentException if the request is null
|
||||
*/
|
||||
CacheableRequestWrapper(HttpServletRequest request) {
|
||||
super(request);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DispatcherType getDispatcherType() {
|
||||
return DispatcherType.REQUEST;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Enumeration<String> getAttributeNames() {
|
||||
return Collections.enumeration(this.attributes.keySet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getAttribute(String name) {
|
||||
return this.attributes.get(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAttribute(String name, Object o) {
|
||||
this.attributes.put(name, o);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeAttribute(String name) {
|
||||
this.attributes.remove(name);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+11
-1
@@ -86,7 +86,7 @@ public class DefaultFilterInvocationSecurityMetadataSource implements FilterInvo
|
||||
|
||||
@Override
|
||||
public Collection<ConfigAttribute> getAttributes(Object object) {
|
||||
final HttpServletRequest request = ((FilterInvocation) object).getRequest();
|
||||
final HttpServletRequest request = getHttpServletRequest(object);
|
||||
int count = 0;
|
||||
for (Map.Entry<RequestMatcher, Collection<ConfigAttribute>> entry : this.requestMap.entrySet()) {
|
||||
if (entry.getKey().matches(request)) {
|
||||
@@ -107,4 +107,14 @@ public class DefaultFilterInvocationSecurityMetadataSource implements FilterInvo
|
||||
return FilterInvocation.class.isAssignableFrom(clazz);
|
||||
}
|
||||
|
||||
private HttpServletRequest getHttpServletRequest(Object object) {
|
||||
if (object instanceof FilterInvocation invocation) {
|
||||
return invocation.getHttpRequest();
|
||||
}
|
||||
if (object instanceof HttpServletRequest request) {
|
||||
return request;
|
||||
}
|
||||
throw new IllegalArgumentException("object must be of type FilterInvocation or HttpServletRequest");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+2
-2
@@ -46,7 +46,7 @@ import org.springframework.security.web.authentication.session.NullAuthenticated
|
||||
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
|
||||
import org.springframework.security.web.context.RequestAttributeSecurityContextRepository;
|
||||
import org.springframework.security.web.context.SecurityContextRepository;
|
||||
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
||||
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.web.filter.GenericFilterBean;
|
||||
@@ -395,7 +395,7 @@ public abstract class AbstractAuthenticationProcessingFilter extends GenericFilt
|
||||
* @param filterProcessesUrl
|
||||
*/
|
||||
public void setFilterProcessesUrl(String filterProcessesUrl) {
|
||||
setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher(filterProcessesUrl));
|
||||
setRequiresAuthenticationRequestMatcher(PathPatternRequestMatcher.withDefaults().matcher(filterProcessesUrl));
|
||||
}
|
||||
|
||||
public final void setRequiresAuthenticationRequestMatcher(RequestMatcher requestMatcher) {
|
||||
|
||||
+6
-11
@@ -65,11 +65,9 @@ import org.springframework.security.web.context.RequestAttributeSecurityContextR
|
||||
import org.springframework.security.web.context.SecurityContextRepository;
|
||||
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
|
||||
import org.springframework.security.web.util.UrlUtils;
|
||||
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.web.filter.GenericFilterBean;
|
||||
import org.springframework.web.util.UrlPathHelper;
|
||||
|
||||
/**
|
||||
* Switch User processing filter responsible for user context switching.
|
||||
@@ -129,9 +127,9 @@ public class SwitchUserFilter extends GenericFilterBean implements ApplicationEv
|
||||
|
||||
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
|
||||
|
||||
private RequestMatcher exitUserMatcher = createMatcher("/logout/impersonate", true);
|
||||
private RequestMatcher exitUserMatcher = createMatcher("/logout/impersonate");
|
||||
|
||||
private RequestMatcher switchUserMatcher = createMatcher("/login/impersonate", true);
|
||||
private RequestMatcher switchUserMatcher = createMatcher("/login/impersonate");
|
||||
|
||||
private String targetUrl;
|
||||
|
||||
@@ -408,7 +406,7 @@ public class SwitchUserFilter extends GenericFilterBean implements ApplicationEv
|
||||
public void setExitUserUrl(String exitUserUrl) {
|
||||
Assert.isTrue(UrlUtils.isValidRedirectUrl(exitUserUrl),
|
||||
"exitUserUrl cannot be empty and must be a valid redirect URL");
|
||||
this.exitUserMatcher = createMatcher(exitUserUrl, false);
|
||||
this.exitUserMatcher = createMatcher(exitUserUrl);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -428,7 +426,7 @@ public class SwitchUserFilter extends GenericFilterBean implements ApplicationEv
|
||||
public void setSwitchUserUrl(String switchUserUrl) {
|
||||
Assert.isTrue(UrlUtils.isValidRedirectUrl(switchUserUrl),
|
||||
"switchUserUrl cannot be empty and must be a valid redirect URL");
|
||||
this.switchUserMatcher = createMatcher(switchUserUrl, false);
|
||||
this.switchUserMatcher = createMatcher(switchUserUrl);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -547,11 +545,8 @@ public class SwitchUserFilter extends GenericFilterBean implements ApplicationEv
|
||||
this.securityContextRepository = securityContextRepository;
|
||||
}
|
||||
|
||||
private static RequestMatcher createMatcher(String pattern, boolean usePathPatterns) {
|
||||
if (usePathPatterns) {
|
||||
return PathPatternRequestMatcher.withDefaults().matcher(HttpMethod.POST, pattern);
|
||||
}
|
||||
return new AntPathRequestMatcher(pattern, "POST", true, new UrlPathHelper());
|
||||
private static RequestMatcher createMatcher(String pattern) {
|
||||
return PathPatternRequestMatcher.withDefaults().matcher(HttpMethod.POST, pattern);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
-251
@@ -1,251 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.web.servlet.util.matcher;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.RequestVariablesExtractor;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
import org.springframework.util.PathMatcher;
|
||||
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
|
||||
import org.springframework.web.servlet.handler.MatchableHandlerMapping;
|
||||
import org.springframework.web.servlet.handler.RequestMatchResult;
|
||||
import org.springframework.web.util.UrlPathHelper;
|
||||
|
||||
/**
|
||||
* A {@link RequestMatcher} that uses Spring MVC's {@link HandlerMappingIntrospector} to
|
||||
* match the path and extract variables.
|
||||
*
|
||||
* <p>
|
||||
* It is important to understand that Spring MVC's matching is relative to the servlet
|
||||
* path. This means if you have mapped any servlet to a path that starts with "/" and is
|
||||
* greater than one, you should also specify the {@link #setServletPath(String)} attribute
|
||||
* to differentiate mappings.
|
||||
* </p>
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @author Eddú Meléndez
|
||||
* @author Evgeniy Cheban
|
||||
* @since 4.1.1
|
||||
* @deprecated Please use {@link PathPatternRequestMatcher} instead
|
||||
*/
|
||||
@Deprecated(forRemoval = true)
|
||||
public class MvcRequestMatcher implements RequestMatcher, RequestVariablesExtractor {
|
||||
|
||||
private final DefaultMatcher defaultMatcher = new DefaultMatcher();
|
||||
|
||||
private final HandlerMappingIntrospector introspector;
|
||||
|
||||
private final String pattern;
|
||||
|
||||
private HttpMethod method;
|
||||
|
||||
private String servletPath;
|
||||
|
||||
public MvcRequestMatcher(HandlerMappingIntrospector introspector, String pattern) {
|
||||
this.introspector = introspector;
|
||||
this.pattern = pattern;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean matches(HttpServletRequest request) {
|
||||
if (notMatchMethodOrServletPath(request)) {
|
||||
return false;
|
||||
}
|
||||
MatchableHandlerMapping mapping = getMapping(request);
|
||||
if (mapping == null) {
|
||||
return this.defaultMatcher.matches(request);
|
||||
}
|
||||
RequestMatchResult matchResult = mapping.match(request, this.pattern);
|
||||
return matchResult != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Deprecated
|
||||
public Map<String, String> extractUriTemplateVariables(HttpServletRequest request) {
|
||||
return matcher(request).getVariables();
|
||||
}
|
||||
|
||||
@Override
|
||||
public MatchResult matcher(HttpServletRequest request) {
|
||||
if (notMatchMethodOrServletPath(request)) {
|
||||
return MatchResult.notMatch();
|
||||
}
|
||||
MatchableHandlerMapping mapping = getMapping(request);
|
||||
if (mapping == null) {
|
||||
return this.defaultMatcher.matcher(request);
|
||||
}
|
||||
RequestMatchResult result = mapping.match(request, this.pattern);
|
||||
return (result != null) ? MatchResult.match(result.extractUriTemplateVariables()) : MatchResult.notMatch();
|
||||
}
|
||||
|
||||
private boolean notMatchMethodOrServletPath(HttpServletRequest request) {
|
||||
return this.method != null && !this.method.name().equals(request.getMethod())
|
||||
|| this.servletPath != null && !this.servletPath.equals(request.getServletPath());
|
||||
}
|
||||
|
||||
private MatchableHandlerMapping getMapping(HttpServletRequest request) {
|
||||
try {
|
||||
return this.introspector.getMatchableHandlerMapping(request);
|
||||
}
|
||||
catch (Throwable ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param method the method to set
|
||||
*/
|
||||
public void setMethod(HttpMethod method) {
|
||||
this.method = method;
|
||||
}
|
||||
|
||||
/**
|
||||
* The servlet path to match on. The default is undefined which means any servlet
|
||||
* path.
|
||||
* @param servletPath the servletPath to set
|
||||
*/
|
||||
public void setServletPath(String servletPath) {
|
||||
this.servletPath = servletPath;
|
||||
}
|
||||
|
||||
protected final String getServletPath() {
|
||||
return this.servletPath;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
MvcRequestMatcher that = (MvcRequestMatcher) o;
|
||||
return Objects.equals(this.pattern, that.pattern) && Objects.equals(this.method, that.method)
|
||||
&& Objects.equals(this.servletPath, that.servletPath);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(this.pattern, this.method, this.servletPath);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("Mvc [pattern='").append(this.pattern).append("'");
|
||||
if (this.servletPath != null) {
|
||||
sb.append(", servletPath='").append(this.servletPath).append("'");
|
||||
}
|
||||
if (this.method != null) {
|
||||
sb.append(", ").append(this.method);
|
||||
}
|
||||
sb.append("]");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private class DefaultMatcher implements RequestMatcher {
|
||||
|
||||
private final UrlPathHelper pathHelper = new UrlPathHelper();
|
||||
|
||||
private final PathMatcher pathMatcher = new AntPathMatcher();
|
||||
|
||||
@Override
|
||||
public boolean matches(HttpServletRequest request) {
|
||||
String lookupPath = this.pathHelper.getLookupPathForRequest(request);
|
||||
return matches(lookupPath);
|
||||
}
|
||||
|
||||
private boolean matches(String lookupPath) {
|
||||
return this.pathMatcher.match(MvcRequestMatcher.this.pattern, lookupPath);
|
||||
}
|
||||
|
||||
@Override
|
||||
public MatchResult matcher(HttpServletRequest request) {
|
||||
String lookupPath = this.pathHelper.getLookupPathForRequest(request);
|
||||
if (matches(lookupPath)) {
|
||||
Map<String, String> variables = this.pathMatcher
|
||||
.extractUriTemplateVariables(MvcRequestMatcher.this.pattern, lookupPath);
|
||||
return MatchResult.match(variables);
|
||||
}
|
||||
return MatchResult.notMatch();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* A builder for {@link MvcRequestMatcher}
|
||||
*
|
||||
* @author Marcus Da Coregio
|
||||
* @since 5.8
|
||||
*/
|
||||
public static final class Builder {
|
||||
|
||||
private final HandlerMappingIntrospector introspector;
|
||||
|
||||
private String servletPath;
|
||||
|
||||
/**
|
||||
* Construct a new instance of this builder
|
||||
*/
|
||||
public Builder(HandlerMappingIntrospector introspector) {
|
||||
this.introspector = introspector;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the servlet path to be used by the {@link MvcRequestMatcher} generated by
|
||||
* this builder
|
||||
* @param servletPath the servlet path to use
|
||||
* @return the {@link Builder} for further configuration
|
||||
*/
|
||||
public Builder servletPath(String servletPath) {
|
||||
this.servletPath = servletPath;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an {@link MvcRequestMatcher} that uses the provided pattern to match
|
||||
* @param pattern the pattern used to match
|
||||
* @return the generated {@link MvcRequestMatcher}
|
||||
*/
|
||||
public MvcRequestMatcher pattern(String pattern) {
|
||||
return pattern(null, pattern);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an {@link MvcRequestMatcher} that uses the provided pattern and HTTP
|
||||
* method to match
|
||||
* @param method the {@link HttpMethod}, can be null
|
||||
* @param pattern the patterns used to match
|
||||
* @return the generated {@link MvcRequestMatcher}
|
||||
*/
|
||||
public MvcRequestMatcher pattern(HttpMethod method, String pattern) {
|
||||
MvcRequestMatcher mvcRequestMatcher = new MvcRequestMatcher(this.introspector, pattern);
|
||||
mvcRequestMatcher.setServletPath(this.servletPath);
|
||||
mvcRequestMatcher.setMethod(method);
|
||||
return mvcRequestMatcher;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-330
@@ -1,330 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2025 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.web.util.matcher;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.util.UrlPathHelper;
|
||||
|
||||
/**
|
||||
* Matcher which compares a pre-defined ant-style pattern against the URL (
|
||||
* {@code servletPath + pathInfo}) of an {@code HttpServletRequest}. The query string of
|
||||
* the URL is ignored and matching is case-insensitive or case-sensitive depending on the
|
||||
* arguments passed into the constructor.
|
||||
* <p>
|
||||
* Using a pattern value of {@code /**} or {@code **} is treated as a universal match,
|
||||
* which will match any request. Patterns which end with {@code /**} (and have no other
|
||||
* wildcards) are optimized by using a substring match — a pattern of
|
||||
* {@code /aaa/**} will match {@code /aaa}, {@code /aaa/} and any sub-directories, such as
|
||||
* {@code /aaa/bbb/ccc}.
|
||||
* </p>
|
||||
* <p>
|
||||
* For all other cases, Spring's {@link AntPathMatcher} is used to perform the match. See
|
||||
* the Spring documentation for this class for comprehensive information on the syntax
|
||||
* used.
|
||||
* </p>
|
||||
*
|
||||
* @author Luke Taylor
|
||||
* @author Rob Winch
|
||||
* @author Eddú Meléndez
|
||||
* @author Evgeniy Cheban
|
||||
* @author Manuel Jordan
|
||||
* @since 3.1
|
||||
* @see org.springframework.util.AntPathMatcher
|
||||
* @deprecated please use {@link PathPatternRequestMatcher} instead
|
||||
*/
|
||||
@Deprecated(forRemoval = true)
|
||||
public final class AntPathRequestMatcher implements RequestMatcher, RequestVariablesExtractor {
|
||||
|
||||
private static final String MATCH_ALL = "/**";
|
||||
|
||||
private final Matcher matcher;
|
||||
|
||||
private final String pattern;
|
||||
|
||||
private final HttpMethod httpMethod;
|
||||
|
||||
private final boolean caseSensitive;
|
||||
|
||||
private final UrlPathHelper urlPathHelper;
|
||||
|
||||
/**
|
||||
* Creates a matcher with the specific pattern which will match all HTTP methods in a
|
||||
* case-sensitive manner.
|
||||
* @param pattern the ant pattern to use for matching
|
||||
* @since 5.8
|
||||
*/
|
||||
public static AntPathRequestMatcher antMatcher(String pattern) {
|
||||
Assert.hasText(pattern, "pattern cannot be empty");
|
||||
return new AntPathRequestMatcher(pattern);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a matcher that will match all request with the supplied HTTP method in a
|
||||
* case-sensitive manner.
|
||||
* @param method the HTTP method. The {@code matches} method will return false if the
|
||||
* incoming request doesn't have the same method.
|
||||
* @since 5.8
|
||||
*/
|
||||
public static AntPathRequestMatcher antMatcher(HttpMethod method) {
|
||||
Assert.notNull(method, "method cannot be null");
|
||||
return new AntPathRequestMatcher(MATCH_ALL, method.name());
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a matcher with the supplied pattern and HTTP method in a case-sensitive
|
||||
* manner.
|
||||
* @param method the HTTP method. The {@code matches} method will return false if the
|
||||
* incoming request doesn't have the same method.
|
||||
* @param pattern the ant pattern to use for matching
|
||||
* @since 5.8
|
||||
*/
|
||||
public static AntPathRequestMatcher antMatcher(HttpMethod method, String pattern) {
|
||||
Assert.notNull(method, "method cannot be null");
|
||||
Assert.hasText(pattern, "pattern cannot be empty");
|
||||
return new AntPathRequestMatcher(pattern, method.name());
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a matcher with the specific pattern which will match all HTTP methods in a
|
||||
* case sensitive manner.
|
||||
* @param pattern the ant pattern to use for matching
|
||||
*/
|
||||
public AntPathRequestMatcher(String pattern) {
|
||||
this(pattern, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a matcher with the supplied pattern and HTTP method in a case sensitive
|
||||
* manner.
|
||||
* @param pattern the ant pattern to use for matching
|
||||
* @param httpMethod the HTTP method. The {@code matches} method will return false if
|
||||
* the incoming request doesn't have the same method.
|
||||
*/
|
||||
public AntPathRequestMatcher(String pattern, String httpMethod) {
|
||||
this(pattern, httpMethod, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a matcher with the supplied pattern which will match the specified Http
|
||||
* method
|
||||
* @param pattern the ant pattern to use for matching
|
||||
* @param httpMethod the HTTP method. The {@code matches} method will return false if
|
||||
* the incoming request doesn't doesn't have the same method.
|
||||
* @param caseSensitive true if the matcher should consider case, else false
|
||||
*/
|
||||
public AntPathRequestMatcher(String pattern, String httpMethod, boolean caseSensitive) {
|
||||
this(pattern, httpMethod, caseSensitive, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a matcher with the supplied pattern which will match the specified Http
|
||||
* method
|
||||
* @param pattern the ant pattern to use for matching
|
||||
* @param httpMethod the HTTP method. The {@code matches} method will return false if
|
||||
* the incoming request doesn't have the same method.
|
||||
* @param caseSensitive true if the matcher should consider case, else false
|
||||
* @param urlPathHelper if non-null, will be used for extracting the path from the
|
||||
* HttpServletRequest
|
||||
*/
|
||||
public AntPathRequestMatcher(String pattern, String httpMethod, boolean caseSensitive,
|
||||
UrlPathHelper urlPathHelper) {
|
||||
Assert.hasText(pattern, "Pattern cannot be null or empty");
|
||||
this.caseSensitive = caseSensitive;
|
||||
if (pattern.equals(MATCH_ALL) || pattern.equals("**")) {
|
||||
pattern = MATCH_ALL;
|
||||
this.matcher = null;
|
||||
}
|
||||
else {
|
||||
// If the pattern ends with {@code /**} and has no other wildcards or path
|
||||
// variables, then optimize to a sub-path match
|
||||
if (pattern.endsWith(MATCH_ALL)
|
||||
&& (pattern.indexOf('?') == -1 && pattern.indexOf('{') == -1 && pattern.indexOf('}') == -1)
|
||||
&& pattern.indexOf("*") == pattern.length() - 2) {
|
||||
this.matcher = new SubpathMatcher(pattern.substring(0, pattern.length() - 3), caseSensitive);
|
||||
}
|
||||
else {
|
||||
this.matcher = new SpringAntMatcher(pattern, caseSensitive);
|
||||
}
|
||||
}
|
||||
this.pattern = pattern;
|
||||
this.httpMethod = StringUtils.hasText(httpMethod) ? HttpMethod.valueOf(httpMethod) : null;
|
||||
this.urlPathHelper = urlPathHelper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the configured pattern (and HTTP-Method) match those of the
|
||||
* supplied request.
|
||||
* @param request the request to match against. The ant pattern will be matched
|
||||
* against the {@code servletPath} + {@code pathInfo} of the request.
|
||||
*/
|
||||
@Override
|
||||
public boolean matches(HttpServletRequest request) {
|
||||
if (this.httpMethod != null && StringUtils.hasText(request.getMethod())
|
||||
&& this.httpMethod != HttpMethod.valueOf(request.getMethod())) {
|
||||
return false;
|
||||
}
|
||||
if (this.pattern.equals(MATCH_ALL)) {
|
||||
return true;
|
||||
}
|
||||
String url = getRequestPath(request);
|
||||
return this.matcher.matches(url);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Deprecated
|
||||
public Map<String, String> extractUriTemplateVariables(HttpServletRequest request) {
|
||||
return matcher(request).getVariables();
|
||||
}
|
||||
|
||||
@Override
|
||||
public MatchResult matcher(HttpServletRequest request) {
|
||||
if (!matches(request)) {
|
||||
return MatchResult.notMatch();
|
||||
}
|
||||
if (this.matcher == null) {
|
||||
return MatchResult.match();
|
||||
}
|
||||
String url = getRequestPath(request);
|
||||
return MatchResult.match(this.matcher.extractUriTemplateVariables(url));
|
||||
}
|
||||
|
||||
private String getRequestPath(HttpServletRequest request) {
|
||||
if (this.urlPathHelper != null) {
|
||||
return this.urlPathHelper.getPathWithinApplication(request);
|
||||
}
|
||||
String url = request.getServletPath();
|
||||
String pathInfo = request.getPathInfo();
|
||||
if (pathInfo != null) {
|
||||
url = StringUtils.hasLength(url) ? url + pathInfo : pathInfo;
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
public String getPattern() {
|
||||
return this.pattern;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (!(obj instanceof AntPathRequestMatcher other)) {
|
||||
return false;
|
||||
}
|
||||
return this.pattern.equals(other.pattern) && this.httpMethod == other.httpMethod
|
||||
&& this.caseSensitive == other.caseSensitive;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = (this.pattern != null) ? this.pattern.hashCode() : 0;
|
||||
result = 31 * result + ((this.httpMethod != null) ? this.httpMethod.hashCode() : 0);
|
||||
result = 31 * result + (this.caseSensitive ? 1231 : 1237);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("Ant [pattern='").append(this.pattern).append("'");
|
||||
if (this.httpMethod != null) {
|
||||
sb.append(", ").append(this.httpMethod);
|
||||
}
|
||||
sb.append("]");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private interface Matcher {
|
||||
|
||||
boolean matches(String path);
|
||||
|
||||
Map<String, String> extractUriTemplateVariables(String path);
|
||||
|
||||
}
|
||||
|
||||
private static final class SpringAntMatcher implements Matcher {
|
||||
|
||||
private final AntPathMatcher antMatcher;
|
||||
|
||||
private final String pattern;
|
||||
|
||||
private SpringAntMatcher(String pattern, boolean caseSensitive) {
|
||||
this.pattern = pattern;
|
||||
this.antMatcher = createMatcher(caseSensitive);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean matches(String path) {
|
||||
return this.antMatcher.match(this.pattern, path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, String> extractUriTemplateVariables(String path) {
|
||||
return this.antMatcher.extractUriTemplateVariables(this.pattern, path);
|
||||
}
|
||||
|
||||
private static AntPathMatcher createMatcher(boolean caseSensitive) {
|
||||
AntPathMatcher matcher = new AntPathMatcher();
|
||||
matcher.setTrimTokens(false);
|
||||
matcher.setCaseSensitive(caseSensitive);
|
||||
return matcher;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Optimized matcher for trailing wildcards
|
||||
*/
|
||||
private static final class SubpathMatcher implements Matcher {
|
||||
|
||||
private final String subpath;
|
||||
|
||||
private final int length;
|
||||
|
||||
private final boolean caseSensitive;
|
||||
|
||||
private SubpathMatcher(String subpath, boolean caseSensitive) {
|
||||
Assert.isTrue(!subpath.contains("*"), "subpath cannot contain \"*\"");
|
||||
this.subpath = caseSensitive ? subpath : subpath.toLowerCase(Locale.ROOT);
|
||||
this.length = subpath.length();
|
||||
this.caseSensitive = caseSensitive;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean matches(String path) {
|
||||
if (!this.caseSensitive) {
|
||||
path = path.toLowerCase(Locale.ROOT);
|
||||
}
|
||||
return path.startsWith(this.subpath) && (path.length() == this.length || path.charAt(this.length) == '/');
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, String> extractUriTemplateVariables(String path) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+8
-6
@@ -22,7 +22,7 @@ import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
||||
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
|
||||
@@ -37,9 +37,11 @@ import static org.mockito.Mockito.verifyNoInteractions;
|
||||
*/
|
||||
public class RequestMatcherRedirectFilterTests {
|
||||
|
||||
private final PathPatternRequestMatcher.Builder builder = PathPatternRequestMatcher.withDefaults();
|
||||
|
||||
@Test
|
||||
public void doFilterWhenRequestMatchThenRedirectToSpecifiedUrl() throws Exception {
|
||||
RequestMatcherRedirectFilter filter = new RequestMatcherRedirectFilter(new AntPathRequestMatcher("/context"),
|
||||
RequestMatcherRedirectFilter filter = new RequestMatcherRedirectFilter(this.builder.matcher("/context"),
|
||||
"/test");
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
@@ -58,7 +60,7 @@ public class RequestMatcherRedirectFilterTests {
|
||||
|
||||
@Test
|
||||
public void doFilterWhenRequestNotMatchThenNextFilter() throws Exception {
|
||||
RequestMatcherRedirectFilter filter = new RequestMatcherRedirectFilter(new AntPathRequestMatcher("/context"),
|
||||
RequestMatcherRedirectFilter filter = new RequestMatcherRedirectFilter(this.builder.matcher("/context"),
|
||||
"/test");
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
@@ -83,21 +85,21 @@ public class RequestMatcherRedirectFilterTests {
|
||||
@Test
|
||||
public void constructWhenRedirectUrlNull() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new RequestMatcherRedirectFilter(new AntPathRequestMatcher("/**"), null))
|
||||
.isThrownBy(() -> new RequestMatcherRedirectFilter(this.builder.matcher("/**"), null))
|
||||
.withMessage("redirectUrl cannot be empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructWhenRedirectUrlEmpty() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new RequestMatcherRedirectFilter(new AntPathRequestMatcher("/**"), ""))
|
||||
.isThrownBy(() -> new RequestMatcherRedirectFilter(this.builder.matcher("/**"), ""))
|
||||
.withMessage("redirectUrl cannot be empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructWhenRedirectUrlBlank() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new RequestMatcherRedirectFilter(new AntPathRequestMatcher("/**"), " "))
|
||||
.isThrownBy(() -> new RequestMatcherRedirectFilter(this.builder.matcher("/**"), " "))
|
||||
.withMessage("redirectUrl cannot be empty");
|
||||
}
|
||||
|
||||
|
||||
-206
@@ -1,206 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.web.access;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
import jakarta.servlet.DispatcherType;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.assertj.core.api.AssertionsForClassTypes;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class HandlerMappingIntrospectorRequestTransformerTests {
|
||||
|
||||
@Mock
|
||||
HandlerMappingIntrospector hmi;
|
||||
|
||||
HandlerMappingIntrospectorRequestTransformer transformer;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
this.transformer = new HandlerMappingIntrospectorRequestTransformer(this.hmi);
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructorWhenHmiIsNullThenIllegalArgumentException() {
|
||||
AssertionsForClassTypes.assertThatExceptionOfType(IllegalArgumentException.class)
|
||||
.isThrownBy(() -> new HandlerMappingIntrospectorRequestTransformer(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void transformThenNewRequestPassedToSetCache() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
HttpServletRequest transformedRequest = this.transformer.transform(request);
|
||||
|
||||
ArgumentCaptor<HttpServletRequest> requestArg = ArgumentCaptor.forClass(HttpServletRequest.class);
|
||||
verify(this.hmi).setCache(requestArg.capture());
|
||||
assertThat(transformedRequest).isNotEqualTo(request);
|
||||
}
|
||||
|
||||
@Test
|
||||
void transformThenResultPassedToSetCache() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
HttpServletRequest transformedRequest = this.transformer.transform(request);
|
||||
|
||||
ArgumentCaptor<HttpServletRequest> requestArg = ArgumentCaptor.forClass(HttpServletRequest.class);
|
||||
verify(this.hmi).setCache(requestArg.capture());
|
||||
assertThat(requestArg.getValue()).isEqualTo(transformedRequest);
|
||||
}
|
||||
|
||||
/**
|
||||
* The request passed into the transformer does not allow interactions on certain
|
||||
* methods, we need to ensure that the methods used by
|
||||
* {@link HandlerMappingIntrospector#setCache(HttpServletRequest)} are overridden.
|
||||
*/
|
||||
@Test
|
||||
void transformThenResultDoesNotDelegateToSetAttribute() {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
|
||||
this.transformer.transform(request);
|
||||
|
||||
ArgumentCaptor<HttpServletRequest> requestArg = ArgumentCaptor.forClass(HttpServletRequest.class);
|
||||
verify(this.hmi).setCache(requestArg.capture());
|
||||
HttpServletRequest transformedRequest = requestArg.getValue();
|
||||
String attrName = "any";
|
||||
String attrValue = "value";
|
||||
transformedRequest.setAttribute(attrName, attrValue);
|
||||
verifyNoInteractions(request);
|
||||
assertThat(transformedRequest.getAttribute(attrName)).isEqualTo(attrValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
void transformThenSetAttributeWorks() {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
|
||||
this.transformer.transform(request);
|
||||
|
||||
ArgumentCaptor<HttpServletRequest> requestArg = ArgumentCaptor.forClass(HttpServletRequest.class);
|
||||
verify(this.hmi).setCache(requestArg.capture());
|
||||
HttpServletRequest transformedRequest = requestArg.getValue();
|
||||
String attrName = "any";
|
||||
String attrValue = "value";
|
||||
transformedRequest.setAttribute(attrName, attrValue);
|
||||
assertThat(transformedRequest.getAttribute(attrName)).isEqualTo(attrValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* The request passed into the transformer does not allow interactions on certain
|
||||
* methods, we need to ensure that the methods used by
|
||||
* {@link HandlerMappingIntrospector#setCache(HttpServletRequest)} are overridden.
|
||||
*/
|
||||
@Test
|
||||
void transformThenResultDoesNotDelegateToGetAttribute() {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
|
||||
this.transformer.transform(request);
|
||||
|
||||
ArgumentCaptor<HttpServletRequest> requestArg = ArgumentCaptor.forClass(HttpServletRequest.class);
|
||||
verify(this.hmi).setCache(requestArg.capture());
|
||||
HttpServletRequest transformedRequest = requestArg.getValue();
|
||||
transformedRequest.getAttribute("any");
|
||||
verifyNoInteractions(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* The request passed into the transformer does not allow interactions on certain
|
||||
* methods, we need to ensure that the methods used by
|
||||
* {@link HandlerMappingIntrospector#setCache(HttpServletRequest)} are overridden.
|
||||
*/
|
||||
@Test
|
||||
void transformThenResultDoesNotDelegateToGetAttributeNames() {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
|
||||
this.transformer.transform(request);
|
||||
|
||||
ArgumentCaptor<HttpServletRequest> requestArg = ArgumentCaptor.forClass(HttpServletRequest.class);
|
||||
verify(this.hmi).setCache(requestArg.capture());
|
||||
HttpServletRequest transformedRequest = requestArg.getValue();
|
||||
transformedRequest.getAttributeNames();
|
||||
verifyNoInteractions(request);
|
||||
}
|
||||
|
||||
@Test
|
||||
void transformThenGetAttributeNamesWorks() {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
|
||||
this.transformer.transform(request);
|
||||
|
||||
ArgumentCaptor<HttpServletRequest> requestArg = ArgumentCaptor.forClass(HttpServletRequest.class);
|
||||
verify(this.hmi).setCache(requestArg.capture());
|
||||
HttpServletRequest transformedRequest = requestArg.getValue();
|
||||
String attrName = "any";
|
||||
String attrValue = "value";
|
||||
transformedRequest.setAttribute(attrName, attrValue);
|
||||
assertThat(Collections.list(transformedRequest.getAttributeNames())).containsExactly(attrName);
|
||||
}
|
||||
|
||||
/**
|
||||
* The request passed into the transformer does not allow interactions on certain
|
||||
* methods, we need to ensure that the methods used by
|
||||
* {@link HandlerMappingIntrospector#setCache(HttpServletRequest)} are overridden.
|
||||
*/
|
||||
@Test
|
||||
void transformThenResultDoesNotDelegateToRemoveAttribute() {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
|
||||
this.transformer.transform(request);
|
||||
|
||||
ArgumentCaptor<HttpServletRequest> requestArg = ArgumentCaptor.forClass(HttpServletRequest.class);
|
||||
verify(this.hmi).setCache(requestArg.capture());
|
||||
HttpServletRequest transformedRequest = requestArg.getValue();
|
||||
transformedRequest.removeAttribute("any");
|
||||
verifyNoInteractions(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* The request passed into the transformer does not allow interactions on certain
|
||||
* methods, we need to ensure that the methods used by
|
||||
* {@link HandlerMappingIntrospector#setCache(HttpServletRequest)} are overridden.
|
||||
*/
|
||||
@Test
|
||||
void transformThenResultDoesNotDelegateToGetDispatcherType() {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
|
||||
this.transformer.transform(request);
|
||||
|
||||
ArgumentCaptor<HttpServletRequest> requestArg = ArgumentCaptor.forClass(HttpServletRequest.class);
|
||||
verify(this.hmi).setCache(requestArg.capture());
|
||||
HttpServletRequest transformedRequest = requestArg.getValue();
|
||||
assertThat(transformedRequest.getDispatcherType()).isEqualTo(DispatcherType.REQUEST);
|
||||
verifyNoInteractions(request);
|
||||
}
|
||||
|
||||
}
|
||||
+9
-7
@@ -22,12 +22,13 @@ import java.util.LinkedHashMap;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.access.ConfigAttribute;
|
||||
import org.springframework.security.access.SecurityConfig;
|
||||
import org.springframework.security.web.FilterInvocation;
|
||||
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
||||
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
@@ -44,9 +45,9 @@ public class DefaultFilterInvocationSecurityMetadataSourceTests {
|
||||
|
||||
private Collection<ConfigAttribute> def = SecurityConfig.createList("ROLE_ONE");
|
||||
|
||||
private void createFids(String pattern, String method) {
|
||||
private void createFids(String pattern, HttpMethod method) {
|
||||
LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<>();
|
||||
requestMap.put(new AntPathRequestMatcher(pattern, method), this.def);
|
||||
requestMap.put(PathPatternRequestMatcher.withDefaults().matcher(method, pattern), this.def);
|
||||
this.fids = new DefaultFilterInvocationSecurityMetadataSource(requestMap);
|
||||
}
|
||||
|
||||
@@ -88,7 +89,7 @@ public class DefaultFilterInvocationSecurityMetadataSourceTests {
|
||||
|
||||
@Test
|
||||
public void httpMethodLookupSucceeds() {
|
||||
createFids("/somepage**", "GET");
|
||||
createFids("/somepage**", HttpMethod.GET);
|
||||
FilterInvocation fi = createFilterInvocation("/somepage", null, null, "GET");
|
||||
Collection<ConfigAttribute> attrs = this.fids.getAttributes(fi);
|
||||
assertThat(attrs).isEqualTo(this.def);
|
||||
@@ -104,7 +105,7 @@ public class DefaultFilterInvocationSecurityMetadataSourceTests {
|
||||
|
||||
@Test
|
||||
public void requestWithDifferentHttpMethodDoesntMatch() {
|
||||
createFids("/somepage**", "GET");
|
||||
createFids("/somepage**", HttpMethod.GET);
|
||||
FilterInvocation fi = createFilterInvocation("/somepage", null, null, "POST");
|
||||
Collection<ConfigAttribute> attrs = this.fids.getAttributes(fi);
|
||||
assertThat(attrs).isNull();
|
||||
@@ -115,8 +116,9 @@ public class DefaultFilterInvocationSecurityMetadataSourceTests {
|
||||
public void mixingPatternsWithAndWithoutHttpMethodsIsSupported() {
|
||||
LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<>();
|
||||
Collection<ConfigAttribute> userAttrs = SecurityConfig.createList("A");
|
||||
requestMap.put(new AntPathRequestMatcher("/user/**", null), userAttrs);
|
||||
requestMap.put(new AntPathRequestMatcher("/teller/**", "GET"), SecurityConfig.createList("B"));
|
||||
requestMap.put(PathPatternRequestMatcher.withDefaults().matcher("/user/**"), userAttrs);
|
||||
requestMap.put(PathPatternRequestMatcher.withDefaults().matcher(HttpMethod.GET, "/teller/**"),
|
||||
SecurityConfig.createList("B"));
|
||||
this.fids = new DefaultFilterInvocationSecurityMetadataSource(requestMap);
|
||||
FilterInvocation fi = createFilterInvocation("/user", null, null, "GET");
|
||||
Collection<ConfigAttribute> attrs = this.fids.getAttributes(fi);
|
||||
|
||||
+9
-8
@@ -28,8 +28,7 @@ import org.springframework.security.authorization.AuthorityAuthorizationManager;
|
||||
import org.springframework.security.authorization.AuthorizationDecision;
|
||||
import org.springframework.security.authorization.SingleResultAuthorizationManager;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
||||
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.AnyRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcherEntry;
|
||||
|
||||
@@ -45,6 +44,8 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
|
||||
*/
|
||||
public class RequestMatcherDelegatingAuthorizationManagerTests {
|
||||
|
||||
private final PathPatternRequestMatcher.Builder builder = PathPatternRequestMatcher.withDefaults();
|
||||
|
||||
@Test
|
||||
public void buildWhenMappingsEmptyThenException() {
|
||||
assertThatIllegalArgumentException()
|
||||
@@ -65,7 +66,7 @@ public class RequestMatcherDelegatingAuthorizationManagerTests {
|
||||
public void addWhenManagerNullThenException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> RequestMatcherDelegatingAuthorizationManager.builder()
|
||||
.add(new MvcRequestMatcher(null, "/grant"), null)
|
||||
.add(this.builder.matcher("/grant"), null)
|
||||
.build())
|
||||
.withMessage("manager cannot be null");
|
||||
}
|
||||
@@ -73,8 +74,8 @@ public class RequestMatcherDelegatingAuthorizationManagerTests {
|
||||
@Test
|
||||
public void checkWhenMultipleMappingsConfiguredThenDelegatesMatchingManager() {
|
||||
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
|
||||
.add(new MvcRequestMatcher(null, "/grant"), SingleResultAuthorizationManager.permitAll())
|
||||
.add(new MvcRequestMatcher(null, "/deny"), SingleResultAuthorizationManager.denyAll())
|
||||
.add(this.builder.matcher(null, "/grant"), SingleResultAuthorizationManager.permitAll())
|
||||
.add(this.builder.matcher(null, "/deny"), SingleResultAuthorizationManager.denyAll())
|
||||
.build();
|
||||
|
||||
Supplier<Authentication> authentication = () -> new TestingAuthenticationToken("user", "password", "ROLE_USER");
|
||||
@@ -97,11 +98,11 @@ public class RequestMatcherDelegatingAuthorizationManagerTests {
|
||||
public void checkWhenMultipleMappingsConfiguredWithConsumerThenDelegatesMatchingManager() {
|
||||
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
|
||||
.mappings((m) -> {
|
||||
m.add(new RequestMatcherEntry<>(new MvcRequestMatcher(null, "/grant"),
|
||||
m.add(new RequestMatcherEntry<>(this.builder.matcher("/grant"),
|
||||
SingleResultAuthorizationManager.permitAll()));
|
||||
m.add(new RequestMatcherEntry<>(AnyRequestMatcher.INSTANCE,
|
||||
AuthorityAuthorizationManager.hasRole("ADMIN")));
|
||||
m.add(new RequestMatcherEntry<>(new MvcRequestMatcher(null, "/afterAny"),
|
||||
m.add(new RequestMatcherEntry<>(this.builder.matcher("/afterAny"),
|
||||
SingleResultAuthorizationManager.permitAll()));
|
||||
})
|
||||
.build();
|
||||
@@ -156,7 +157,7 @@ public class RequestMatcherDelegatingAuthorizationManagerTests {
|
||||
.isThrownBy(() -> RequestMatcherDelegatingAuthorizationManager.builder()
|
||||
.anyRequest()
|
||||
.authenticated()
|
||||
.requestMatchers(new AntPathRequestMatcher("/authenticated"))
|
||||
.requestMatchers(this.builder.matcher("/authenticated"))
|
||||
.authenticated()
|
||||
.build())
|
||||
.withMessage("Can't configure requestMatchers after anyRequest");
|
||||
|
||||
+4
-3
@@ -47,7 +47,7 @@ import org.springframework.security.web.authentication.session.SessionAuthentica
|
||||
import org.springframework.security.web.context.RequestAttributeSecurityContextRepository;
|
||||
import org.springframework.security.web.context.SecurityContextRepository;
|
||||
import org.springframework.security.web.firewall.DefaultHttpFirewall;
|
||||
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
||||
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
@@ -239,7 +239,8 @@ public class AbstractAuthenticationProcessingFilterTests {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
// Setup our test object, to grant access
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter(
|
||||
new AntPathRequestMatcher("/j_eradicate_corona_virus"), mock(AuthenticationManager.class));
|
||||
PathPatternRequestMatcher.withDefaults().matcher("/j_eradicate_corona_virus"),
|
||||
mock(AuthenticationManager.class));
|
||||
filter.setSessionAuthenticationStrategy(mock(SessionAuthenticationStrategy.class));
|
||||
filter.setAuthenticationSuccessHandler(this.successHandler);
|
||||
filter.setAuthenticationFailureHandler(this.failureHandler);
|
||||
@@ -273,7 +274,7 @@ public class AbstractAuthenticationProcessingFilterTests {
|
||||
filter.setAuthenticationManager(mock(AuthenticationManager.class));
|
||||
filter.setAuthenticationSuccessHandler(this.successHandler);
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> filter.setFilterProcessesUrl(null))
|
||||
.withMessage("Pattern cannot be null or empty");
|
||||
.withMessage("pattern cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+5
-5
@@ -23,7 +23,7 @@ import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.AuthenticationServiceException;
|
||||
import org.springframework.security.authentication.TestingAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
||||
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
@@ -44,8 +44,8 @@ public class RequestMatcherDelegatingAuthenticationManagerResolverTests {
|
||||
public void resolveWhenMatchesThenReturnsAuthenticationManager() {
|
||||
RequestMatcherDelegatingAuthenticationManagerResolver resolver = RequestMatcherDelegatingAuthenticationManagerResolver
|
||||
.builder()
|
||||
.add(new AntPathRequestMatcher("/one/**"), this.one)
|
||||
.add(new AntPathRequestMatcher("/two/**"), this.two)
|
||||
.add(PathPatternRequestMatcher.withDefaults().matcher("/one/**"), this.one)
|
||||
.add(PathPatternRequestMatcher.withDefaults().matcher("/two/**"), this.two)
|
||||
.build();
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/one/location");
|
||||
@@ -57,8 +57,8 @@ public class RequestMatcherDelegatingAuthenticationManagerResolverTests {
|
||||
public void resolveWhenDoesNotMatchThenReturnsDefaultAuthenticationManager() {
|
||||
RequestMatcherDelegatingAuthenticationManagerResolver resolver = RequestMatcherDelegatingAuthenticationManagerResolver
|
||||
.builder()
|
||||
.add(new AntPathRequestMatcher("/one/**"), this.one)
|
||||
.add(new AntPathRequestMatcher("/two/**"), this.two)
|
||||
.add(PathPatternRequestMatcher.withDefaults().matcher("/one/**"), this.one)
|
||||
.add(PathPatternRequestMatcher.withDefaults().matcher("/two/**"), this.two)
|
||||
.build();
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/wrong/location");
|
||||
|
||||
+5
-3
@@ -41,7 +41,7 @@ import org.springframework.security.web.WebAttributes;
|
||||
import org.springframework.security.web.authentication.ForwardAuthenticationFailureHandler;
|
||||
import org.springframework.security.web.authentication.ForwardAuthenticationSuccessHandler;
|
||||
import org.springframework.security.web.context.SecurityContextRepository;
|
||||
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
||||
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
@@ -60,6 +60,8 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
*/
|
||||
public class AbstractPreAuthenticatedProcessingFilterTests {
|
||||
|
||||
private final PathPatternRequestMatcher.Builder builder = PathPatternRequestMatcher.withDefaults();
|
||||
|
||||
private AbstractPreAuthenticatedProcessingFilter filter;
|
||||
|
||||
@BeforeEach
|
||||
@@ -367,7 +369,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
|
||||
filter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/no-matching"));
|
||||
filter.setRequiresAuthenticationRequestMatcher(this.builder.matcher("/no-matching"));
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
filter.setAuthenticationManager(am);
|
||||
filter.afterPropertiesSet();
|
||||
@@ -381,7 +383,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
|
||||
filter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/**"));
|
||||
filter.setRequiresAuthenticationRequestMatcher(this.builder.matcher("/**"));
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
filter.setAuthenticationManager(am);
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
+2
-2
@@ -46,7 +46,7 @@ import org.springframework.security.web.authentication.AuthenticationConverter;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetails;
|
||||
import org.springframework.security.web.context.RequestAttributeSecurityContextRepository;
|
||||
import org.springframework.security.web.context.SecurityContextRepository;
|
||||
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
||||
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||
import org.springframework.web.util.WebUtils;
|
||||
|
||||
@@ -531,7 +531,7 @@ public class BasicAuthenticationFilterTests {
|
||||
|
||||
static class TestAuthenticationConverter implements AuthenticationConverter {
|
||||
|
||||
private final RequestMatcher matcher = AntPathRequestMatcher.antMatcher("/ignored");
|
||||
private final RequestMatcher matcher = PathPatternRequestMatcher.withDefaults().matcher("/ignored");
|
||||
|
||||
private final BasicAuthenticationConverter delegate = new BasicAuthenticationConverter();
|
||||
|
||||
|
||||
-275
@@ -1,275 +0,0 @@
|
||||
/*
|
||||
* Copyright 2012-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.web.servlet.util.matcher;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Captor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
|
||||
import org.springframework.web.servlet.handler.MatchableHandlerMapping;
|
||||
import org.springframework.web.servlet.handler.RequestMatchResult;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
* @author Eddú Meléndez
|
||||
* @author Evgeniy Cheban
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
public class MvcRequestMatcherTests {
|
||||
|
||||
@Mock
|
||||
HandlerMappingIntrospector introspector;
|
||||
|
||||
@Mock
|
||||
MatchableHandlerMapping mapping;
|
||||
|
||||
@Mock
|
||||
RequestMatchResult result;
|
||||
|
||||
@Captor
|
||||
ArgumentCaptor<String> pattern;
|
||||
|
||||
MockHttpServletRequest request;
|
||||
|
||||
MvcRequestMatcher matcher;
|
||||
|
||||
@BeforeEach
|
||||
public void setup() {
|
||||
this.request = new MockHttpServletRequest();
|
||||
this.request.setMethod("GET");
|
||||
this.request.setServletPath("/path");
|
||||
this.matcher = new MvcRequestMatcher(this.introspector, "/path");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void extractUriTemplateVariablesSuccess() throws Exception {
|
||||
this.matcher = new MvcRequestMatcher(this.introspector, "/{p}");
|
||||
given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(null);
|
||||
assertThat(this.matcher.extractUriTemplateVariables(this.request)).containsEntry("p", "path");
|
||||
assertThat(this.matcher.matcher(this.request).getVariables()).containsEntry("p", "path");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void extractUriTemplateVariablesFail() throws Exception {
|
||||
given(this.result.extractUriTemplateVariables()).willReturn(Collections.<String, String>emptyMap());
|
||||
given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(this.mapping);
|
||||
given(this.mapping.match(eq(this.request), this.pattern.capture())).willReturn(this.result);
|
||||
assertThat(this.matcher.extractUriTemplateVariables(this.request)).isEmpty();
|
||||
assertThat(this.matcher.matcher(this.request).getVariables()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void extractUriTemplateVariablesDefaultSuccess() throws Exception {
|
||||
this.matcher = new MvcRequestMatcher(this.introspector, "/{p}");
|
||||
given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(null);
|
||||
assertThat(this.matcher.extractUriTemplateVariables(this.request)).containsEntry("p", "path");
|
||||
assertThat(this.matcher.matcher(this.request).getVariables()).containsEntry("p", "path");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void extractUriTemplateVariablesDefaultFail() throws Exception {
|
||||
this.matcher = new MvcRequestMatcher(this.introspector, "/nomatch/{p}");
|
||||
given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(null);
|
||||
assertThat(this.matcher.extractUriTemplateVariables(this.request)).isEmpty();
|
||||
assertThat(this.matcher.matcher(this.request).getVariables()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesServletPathTrue() throws Exception {
|
||||
given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(this.mapping);
|
||||
given(this.mapping.match(eq(this.request), this.pattern.capture())).willReturn(this.result);
|
||||
this.matcher.setServletPath("/spring");
|
||||
this.request.setServletPath("/spring");
|
||||
assertThat(this.matcher.matches(this.request)).isTrue();
|
||||
assertThat(this.pattern.getValue()).isEqualTo("/path");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesServletPathFalse() {
|
||||
this.matcher.setServletPath("/spring");
|
||||
this.request.setServletPath("/");
|
||||
assertThat(this.matcher.matches(this.request)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesPathOnlyTrue() throws Exception {
|
||||
given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(this.mapping);
|
||||
given(this.mapping.match(eq(this.request), this.pattern.capture())).willReturn(this.result);
|
||||
assertThat(this.matcher.matches(this.request)).isTrue();
|
||||
assertThat(this.pattern.getValue()).isEqualTo("/path");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesDefaultMatches() throws Exception {
|
||||
given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(null);
|
||||
assertThat(this.matcher.matches(this.request)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesDefaultDoesNotMatch() throws Exception {
|
||||
this.request.setServletPath("/other");
|
||||
given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(null);
|
||||
assertThat(this.matcher.matches(this.request)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesPathOnlyFalse() throws Exception {
|
||||
given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(this.mapping);
|
||||
assertThat(this.matcher.matches(this.request)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesMethodAndPathTrue() throws Exception {
|
||||
this.matcher.setMethod(HttpMethod.GET);
|
||||
given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(this.mapping);
|
||||
given(this.mapping.match(eq(this.request), this.pattern.capture())).willReturn(this.result);
|
||||
assertThat(this.matcher.matches(this.request)).isTrue();
|
||||
assertThat(this.pattern.getValue()).isEqualTo("/path");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesMethodAndPathFalseMethod() {
|
||||
this.matcher.setMethod(HttpMethod.POST);
|
||||
assertThat(this.matcher.matches(this.request)).isFalse();
|
||||
// method compare should be done first since faster
|
||||
verifyNoMoreInteractions(this.introspector);
|
||||
}
|
||||
|
||||
/**
|
||||
* Malicious users can specify any HTTP Method to create a stacktrace and try to
|
||||
* expose useful information about the system. We should ensure we ignore invalid HTTP
|
||||
* methods.
|
||||
*/
|
||||
@Test
|
||||
public void matchesInvalidMethodOnRequest() {
|
||||
this.matcher.setMethod(HttpMethod.GET);
|
||||
this.request.setMethod("invalid");
|
||||
assertThat(this.matcher.matches(this.request)).isFalse();
|
||||
// method compare should be done first since faster
|
||||
verifyNoMoreInteractions(this.introspector);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesMethodAndPathFalsePath() throws Exception {
|
||||
this.matcher.setMethod(HttpMethod.GET);
|
||||
given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(this.mapping);
|
||||
assertThat(this.matcher.matches(this.request)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesGetMatchableHandlerMappingNull() {
|
||||
assertThat(this.matcher.matches(this.request)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesGetMatchableHandlerMappingThrows() throws Exception {
|
||||
given(this.introspector.getMatchableHandlerMapping(this.request))
|
||||
.willThrow(new HttpRequestMethodNotSupportedException(this.request.getMethod()));
|
||||
assertThat(this.matcher.matches(this.request)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void toStringWhenAll() {
|
||||
this.matcher.setMethod(HttpMethod.GET);
|
||||
this.matcher.setServletPath("/spring");
|
||||
assertThat(this.matcher.toString()).isEqualTo("Mvc [pattern='/path', servletPath='/spring', GET]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void toStringWhenHttpMethod() {
|
||||
this.matcher.setMethod(HttpMethod.GET);
|
||||
assertThat(this.matcher.toString()).isEqualTo("Mvc [pattern='/path', GET]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void toStringWhenServletPath() {
|
||||
this.matcher.setServletPath("/spring");
|
||||
assertThat(this.matcher.toString()).isEqualTo("Mvc [pattern='/path', servletPath='/spring']");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void toStringWhenOnlyPattern() {
|
||||
assertThat(this.matcher.toString()).isEqualTo("Mvc [pattern='/path']");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matcherWhenMethodNotMatchesThenNotMatchResult() {
|
||||
this.matcher.setMethod(HttpMethod.POST);
|
||||
assertThat(this.matcher.matcher(this.request).isMatch()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matcherWhenMethodMatchesThenMatchResult() {
|
||||
this.matcher.setMethod(HttpMethod.GET);
|
||||
assertThat(this.matcher.matcher(this.request).isMatch()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matcherWhenServletPathNotMatchesThenNotMatchResult() {
|
||||
this.matcher.setServletPath("/spring");
|
||||
assertThat(this.matcher.matcher(this.request).isMatch()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matcherWhenServletPathMatchesThenMatchResult() {
|
||||
this.matcher.setServletPath("/path");
|
||||
assertThat(this.matcher.matcher(this.request).isMatch()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void builderWhenServletPathThenServletPathPresent() {
|
||||
MvcRequestMatcher matcher = new MvcRequestMatcher.Builder(this.introspector).servletPath("/path")
|
||||
.pattern("/endpoint");
|
||||
assertThat(matcher.getServletPath()).isEqualTo("/path");
|
||||
assertThat(ReflectionTestUtils.getField(matcher, "pattern")).isEqualTo("/endpoint");
|
||||
assertThat(ReflectionTestUtils.getField(matcher, "method")).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void builderWhenPatternThenPatternPresent() {
|
||||
MvcRequestMatcher matcher = new MvcRequestMatcher.Builder(this.introspector).pattern("/endpoint");
|
||||
assertThat(matcher.getServletPath()).isNull();
|
||||
assertThat(ReflectionTestUtils.getField(matcher, "pattern")).isEqualTo("/endpoint");
|
||||
assertThat(ReflectionTestUtils.getField(matcher, "method")).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void builderWhenMethodAndPatternThenMethodAndPatternPresent() {
|
||||
MvcRequestMatcher matcher = new MvcRequestMatcher.Builder(this.introspector).pattern(HttpMethod.GET,
|
||||
"/endpoint");
|
||||
assertThat(matcher.getServletPath()).isNull();
|
||||
assertThat(ReflectionTestUtils.getField(matcher, "pattern")).isEqualTo("/endpoint");
|
||||
assertThat(ReflectionTestUtils.getField(matcher, "method")).isEqualTo(HttpMethod.GET);
|
||||
}
|
||||
|
||||
}
|
||||
+2
-1
@@ -27,6 +27,7 @@ import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcher.MatchResult;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
@@ -59,7 +60,7 @@ public class AndRequestMatcherTests {
|
||||
|
||||
@Test
|
||||
public void constructorListOfDoesNotThrowNullPointer() {
|
||||
new AndRequestMatcher(List.of(new AntPathRequestMatcher("/test")));
|
||||
new AndRequestMatcher(List.of(PathPatternRequestMatcher.withDefaults().matcher("/test")));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
-266
@@ -1,266 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.web.util.matcher;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.web.util.UrlPathHelper;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher;
|
||||
|
||||
/**
|
||||
* @author Luke Taylor
|
||||
* @author Rob Winch
|
||||
* @author Evgeniy Cheban
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
public class AntPathRequestMatcherTests {
|
||||
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
|
||||
@Test
|
||||
public void matchesWhenUrlPathHelperThenMatchesOnRequestUri() {
|
||||
AntPathRequestMatcher matcher = new AntPathRequestMatcher("/foo/bar", null, true, new UrlPathHelper());
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo/bar");
|
||||
assertThat(matcher.matches(request)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void singleWildcardMatchesAnyPath() {
|
||||
AntPathRequestMatcher matcher = new AntPathRequestMatcher("/**");
|
||||
assertThat(matcher.getPattern()).isEqualTo("/**");
|
||||
assertThat(matcher.matches(createRequest("/blah"))).isTrue();
|
||||
matcher = new AntPathRequestMatcher("**");
|
||||
assertThat(matcher.matches(createRequest("/blah"))).isTrue();
|
||||
assertThat(matcher.matches(createRequest(""))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void trailingWildcardMatchesCorrectly() {
|
||||
AntPathRequestMatcher matcher = new AntPathRequestMatcher("/blah/blAh/**", null, false);
|
||||
assertThat(matcher.matches(createRequest("/BLAH/blah"))).isTrue();
|
||||
assertThat(matcher.matches(createRequest("/blah/bleh"))).isFalse();
|
||||
assertThat(matcher.matches(createRequest("/blah/blah/"))).isTrue();
|
||||
assertThat(matcher.matches(createRequest("/blah/blah/xxx"))).isTrue();
|
||||
assertThat(matcher.matches(createRequest("/blah/blaha"))).isFalse();
|
||||
assertThat(matcher.matches(createRequest("/blah/bleh/"))).isFalse();
|
||||
MockHttpServletRequest request = createRequest("/blah/");
|
||||
request.setPathInfo("blah/bleh");
|
||||
assertThat(matcher.matches(request)).isTrue();
|
||||
matcher = new AntPathRequestMatcher("/bl?h/blAh/**", null, false);
|
||||
assertThat(matcher.matches(createRequest("/BLAH/Blah/aaa/"))).isTrue();
|
||||
assertThat(matcher.matches(createRequest("/bleh/Blah"))).isTrue();
|
||||
matcher = new AntPathRequestMatcher("/blAh/**/blah/**", null, false);
|
||||
assertThat(matcher.matches(createRequest("/blah/blah"))).isTrue();
|
||||
assertThat(matcher.matches(createRequest("/blah/bleh"))).isFalse();
|
||||
assertThat(matcher.matches(createRequest("/blah/aaa/blah/bbb"))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void trailingWildcardWithVariableMatchesCorrectly() {
|
||||
AntPathRequestMatcher matcher = new AntPathRequestMatcher("/{id}/blAh/**", null, false);
|
||||
assertThat(matcher.matches(createRequest("/1234/blah"))).isTrue();
|
||||
assertThat(matcher.matches(createRequest("/4567/bleh"))).isFalse();
|
||||
assertThat(matcher.matches(createRequest("/paskos/blah/"))).isTrue();
|
||||
assertThat(matcher.matches(createRequest("/12345/blah/xxx"))).isTrue();
|
||||
assertThat(matcher.matches(createRequest("/12345/blaha"))).isFalse();
|
||||
assertThat(matcher.matches(createRequest("/paskos/bleh/"))).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nontrailingWildcardWithVariableMatchesCorrectly() {
|
||||
AntPathRequestMatcher matcher = new AntPathRequestMatcher("/**/{id}");
|
||||
assertThat(matcher.matches(createRequest("/blah/1234"))).isTrue();
|
||||
assertThat(matcher.matches(createRequest("/bleh/4567"))).isTrue();
|
||||
assertThat(matcher.matches(createRequest("/paskos/blah/"))).isFalse();
|
||||
assertThat(matcher.matches(createRequest("/12345/blah/xxx"))).isTrue();
|
||||
assertThat(matcher.matches(createRequest("/12345/blaha"))).isTrue();
|
||||
assertThat(matcher.matches(createRequest("/paskos/bleh/"))).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestHasNullMethodMatches() {
|
||||
AntPathRequestMatcher matcher = new AntPathRequestMatcher("/something/*", "GET");
|
||||
HttpServletRequest request = createRequestWithNullMethod("/something/here");
|
||||
assertThat(matcher.matches(request)).isTrue();
|
||||
}
|
||||
|
||||
// SEC-2084
|
||||
@Test
|
||||
public void requestHasNullMethodNoMatch() {
|
||||
AntPathRequestMatcher matcher = new AntPathRequestMatcher("/something/*", "GET");
|
||||
HttpServletRequest request = createRequestWithNullMethod("/nomatch");
|
||||
assertThat(matcher.matches(request)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestHasNullMethodAndNullMatcherMatches() {
|
||||
AntPathRequestMatcher matcher = new AntPathRequestMatcher("/something/*");
|
||||
MockHttpServletRequest request = createRequest("/something/here");
|
||||
request.setMethod(null);
|
||||
assertThat(matcher.matches(request)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestHasNullMethodAndNullMatcherNoMatch() {
|
||||
AntPathRequestMatcher matcher = new AntPathRequestMatcher("/something/*");
|
||||
MockHttpServletRequest request = createRequest("/nomatch");
|
||||
request.setMethod(null);
|
||||
assertThat(matcher.matches(request)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void exactMatchOnlyMatchesIdenticalPath() {
|
||||
AntPathRequestMatcher matcher = new AntPathRequestMatcher("/login.html");
|
||||
assertThat(matcher.matches(createRequest("/login.html"))).isTrue();
|
||||
assertThat(matcher.matches(createRequest("/login.html/"))).isFalse();
|
||||
assertThat(matcher.matches(createRequest("/login.html/blah"))).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void httpMethodSpecificMatchOnlyMatchesRequestsWithCorrectMethod() {
|
||||
AntPathRequestMatcher matcher = new AntPathRequestMatcher("/blah", "GET");
|
||||
MockHttpServletRequest request = createRequest("/blah");
|
||||
request.setMethod("GET");
|
||||
assertThat(matcher.matches(request)).isTrue();
|
||||
request.setMethod("POST");
|
||||
assertThat(matcher.matches(request)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void caseSensitive() {
|
||||
MockHttpServletRequest request = createRequest("/UPPER");
|
||||
assertThat(new AntPathRequestMatcher("/upper", null, true).matches(request)).isFalse();
|
||||
assertThat(new AntPathRequestMatcher("/upper", "POST", true).matches(request)).isFalse();
|
||||
assertThat(new AntPathRequestMatcher("/upper", "GET", true).matches(request)).isFalse();
|
||||
assertThat(new AntPathRequestMatcher("/upper", null, false).matches(request)).isTrue();
|
||||
assertThat(new AntPathRequestMatcher("/upper", "POST", false).matches(request)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void spacesInPathSegmentsAreNotIgnored() {
|
||||
AntPathRequestMatcher matcher = new AntPathRequestMatcher("/path/*/bar");
|
||||
MockHttpServletRequest request = createRequest("/path /foo/bar");
|
||||
assertThat(matcher.matches(request)).isFalse();
|
||||
matcher = new AntPathRequestMatcher("/path/foo");
|
||||
request = createRequest("/path /foo");
|
||||
assertThat(matcher.matches(request)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void equalsBehavesCorrectly() {
|
||||
// Both universal wildcard options should be equal
|
||||
assertThat(new AntPathRequestMatcher("**")).isEqualTo(new AntPathRequestMatcher("/**"));
|
||||
assertThat(new AntPathRequestMatcher("/xyz")).isEqualTo(new AntPathRequestMatcher("/xyz"));
|
||||
assertThat(new AntPathRequestMatcher("/xyz", "POST")).isEqualTo(new AntPathRequestMatcher("/xyz", "POST"));
|
||||
assertThat(new AntPathRequestMatcher("/xyz", "POST")).isNotEqualTo(new AntPathRequestMatcher("/xyz", "GET"));
|
||||
assertThat(new AntPathRequestMatcher("/xyz")).isNotEqualTo(new AntPathRequestMatcher("/xxx"));
|
||||
assertThat(new AntPathRequestMatcher("/xyz").equals(AnyRequestMatcher.INSTANCE)).isFalse();
|
||||
assertThat(new AntPathRequestMatcher("/xyz", "GET", false))
|
||||
.isNotEqualTo(new AntPathRequestMatcher("/xyz", "GET", true));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void toStringIsOk() {
|
||||
new AntPathRequestMatcher("/blah").toString();
|
||||
new AntPathRequestMatcher("/blah", "GET").toString();
|
||||
}
|
||||
|
||||
// SEC-2831
|
||||
@Test
|
||||
public void matchesWithInvalidMethod() {
|
||||
AntPathRequestMatcher matcher = new AntPathRequestMatcher("/blah", "GET");
|
||||
MockHttpServletRequest request = createRequest("/blah");
|
||||
request.setMethod("INVALID");
|
||||
assertThat(matcher.matches(request)).isFalse();
|
||||
}
|
||||
|
||||
// gh-9285
|
||||
@Test
|
||||
public void matcherWhenMatchAllPatternThenMatchResult() {
|
||||
AntPathRequestMatcher matcher = new AntPathRequestMatcher("/**");
|
||||
MockHttpServletRequest request = createRequest("/blah");
|
||||
assertThat(matcher.matcher(request).isMatch()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void staticAntMatcherWhenPatternProvidedThenPattern() {
|
||||
AntPathRequestMatcher matcher = antMatcher("/path");
|
||||
assertThat(matcher.getPattern()).isEqualTo("/path");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void staticAntMatcherWhenMethodProvidedThenMatchAll() {
|
||||
AntPathRequestMatcher matcher = antMatcher(HttpMethod.GET);
|
||||
assertThat(ReflectionTestUtils.getField(matcher, "httpMethod")).isEqualTo(HttpMethod.GET);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void staticAntMatcherWhenMethodAndPatternProvidedThenMatchAll() {
|
||||
AntPathRequestMatcher matcher = antMatcher(HttpMethod.POST, "/path");
|
||||
assertThat(matcher.getPattern()).isEqualTo("/path");
|
||||
assertThat(ReflectionTestUtils.getField(matcher, "httpMethod")).isEqualTo(HttpMethod.POST);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void staticAntMatcherWhenMethodNullThenException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> antMatcher((HttpMethod) null))
|
||||
.withMessage("method cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void staticAntMatcherWhenPatternNullThenException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> antMatcher((String) null))
|
||||
.withMessage("pattern cannot be empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void forMethodWhenMethodThenMatches() {
|
||||
AntPathRequestMatcher matcher = antMatcher(HttpMethod.POST);
|
||||
MockHttpServletRequest request = createRequest("/path");
|
||||
assertThat(matcher.matches(request)).isTrue();
|
||||
request.setServletPath("/another-path/second");
|
||||
assertThat(matcher.matches(request)).isTrue();
|
||||
request.setMethod("GET");
|
||||
assertThat(matcher.matches(request)).isFalse();
|
||||
}
|
||||
|
||||
private HttpServletRequest createRequestWithNullMethod(String path) {
|
||||
given(this.request.getServletPath()).willReturn(path);
|
||||
return this.request;
|
||||
}
|
||||
|
||||
private MockHttpServletRequest createRequest(String path) {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setQueryString("doesntMatter");
|
||||
request.setServletPath(path);
|
||||
request.setMethod("POST");
|
||||
return request;
|
||||
}
|
||||
|
||||
}
|
||||
+2
-1
@@ -27,6 +27,7 @@ import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcher.MatchResult;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
@@ -60,7 +61,7 @@ public class OrRequestMatcherTests {
|
||||
|
||||
@Test
|
||||
public void constructorListOfDoesNotThrowNullPointer() {
|
||||
new OrRequestMatcher(List.of(new AntPathRequestMatcher("/test")));
|
||||
new OrRequestMatcher(List.of(PathPatternRequestMatcher.withDefaults().matcher("/test")));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in New Issue
Block a user