spring mvc url匹配禁用后缀访问操作
作者:Felix Zh 发布时间:2021-11-19 23:57:34
spring mvc url匹配禁用后缀访问
在spring mvc中默认 访问url 加任意后缀名都能访问
比如:你想访问 /login ,但是通过 /login.do /login.action /login.json 都能访问
通常来说可能没有影响,但对于权限控制,这就严重了。
权限控制通常有两种思路:
1)弱权限控制
允许所有url通过,仅对个别重要的url做权限控制。此种方式比较简单,不需要对所有url资源进行配置,只配置重要的资源。
2)强权限控制
默认禁止所有url请求通过,仅开放授权的资源。此种方式对所有的url资源进行控制。在系统种需要整理所有的请求,或者某一目录下所有的url资源。这种方式安全控制比较严格,操作麻烦,但相对安全。
如果用第二种方式,则上面spring mvc的访问策略对安全没有影响。
但如果用第一种安全策略,则会有很大的安全风险。
例如:我们控制了/login 的访问,但是我们默认除/login的资源不受权限控制约束,那么攻击者就可以用 /login.do /login.xxx 来访问我们的资源。
在spring 3.1之后,url找对应方法的处理步骤,第一步,直接调用RequestMappingHandlerMapping查找到相应的处理方法,第二步,调用RequestMappingHandlerAdapter进行处理
我们在RequestMappingHandlerMapping中可以看到
/**
* Whether to use suffix pattern match for registered file extensions only
* when matching patterns to requests.
* <p>If enabled, a controller method mapped to "/users" also matches to
* "/users.json" assuming ".json" is a file extension registered with the
* provided {@link #setContentNegotiationManager(ContentNegotiationManager)
* contentNegotiationManager}. This can be useful for allowing only specific
* URL extensions to be used as well as in cases where a "." in the URL path
* can lead to ambiguous interpretation of path variable content, (e.g. given
* "/users/{user}" and incoming URLs such as "/users/john.j.joe" and
* "/users/john.j.joe.json").
* <p>If enabled, this flag also enables
* {@link #setUseSuffixPatternMatch(boolean) useSuffixPatternMatch}. The
* default value is {@code false}.
*/
public void setUseRegisteredSuffixPatternMatch(boolean useRegisteredSuffixPatternMatch) {
this.useRegisteredSuffixPatternMatch = useRegisteredSuffixPatternMatch;
this.useSuffixPatternMatch = (useRegisteredSuffixPatternMatch || this.useSuffixPatternMatch);
}
那么如何来配置呢?
<mvc:annotation-driven>
<mvc:path-matching suffix-pattern="false" />
</mvc:annotation-driven>
在匹配模式时是否使用后缀模式匹配,默认值为true。这样你想访问 /login ,通过 /login.* 就不能访问了。
spring mvc 之 请求url 带后缀的情况
RequestMappingInfoHandlerMapping 在处理http请求的时候, 如果 请求url 有后缀,如果找不到精确匹配的那个@RequestMapping方法。
那么,就把后缀去掉,然后.* 去匹配,这样,一般都可以匹配。 比如有一个@RequestMapping("/rest"), 那么精确匹配的情况下, 只会匹配/rest请求。
但如果我前端发来一个 /rest.abcdef 这样的请求, 又没有配置 @RequestMapping("/rest.abcdef") 这样映射的情况下, 那么@RequestMapping("/rest") 就会生效。
原理呢?处理链是这样的:
at org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getMatchingPattern(PatternsRequestCondition.java:254)
at org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getMatchingPatterns(PatternsRequestCondition.java:230)
at org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getMatchingCondition(PatternsRequestCondition.java:210)
at org.springframework.web.servlet.mvc.method.RequestMappingInfo.getMatchingCondition(RequestMappingInfo.java:214)
at org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping.getMatchingMapping(RequestMappingInfoHandlerMapping.java:79)
at org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping.getMatchingMapping(RequestMappingInfoHandlerMapping.java:56)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.addMatchingMappings(AbstractHandlerMethodMapping.java:358)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.lookupHandlerMethod(AbstractHandlerMethodMapping.java:328)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:299)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:57)
at org.springframework.web.servlet.handler.AbstractHandlerMapping.getHandler(AbstractHandlerMapping.java:299)
at org.springframework.web.servlet.DispatcherServlet.getHandler(DispatcherServlet.java:1104)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:916)
关键是PatternsRequestCondition, 具体来说是这个方法:
AbstractHandlerMethodMapping 的getHandlerInternal:
protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {
String lookupPath = this.getUrlPathHelper().getLookupPathForRequest(request);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Looking up handler method for path " + lookupPath);
}
HandlerMethod handlerMethod = this.lookupHandlerMethod(lookupPath, request);// 这里是关键,它去寻找,找到了就找到了,找不到就不会再去寻找了
if (this.logger.isDebugEnabled()) {
if (handlerMethod != null) {
this.logger.debug("Returning handler method [" + handlerMethod + "]");
} else {
this.logger.debug("Did not find handler method for [" + lookupPath + "]");
}
}
return handlerMethod != null ? handlerMethod.createWithResolvedBean() : null;
}
protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
List<AbstractHandlerMethodMapping<T>.Match> matches = new ArrayList();
List<T> directPathMatches = (List)this.urlMap.get(lookupPath); // directPathMatches, 直接匹配, 也可以说是 精确匹配
if (directPathMatches != null) {
this.addMatchingMappings(directPathMatches, matches, request);// 如果能够精确匹配, 就会进来这里
}
if (matches.isEmpty()) {
this.addMatchingMappings(this.handlerMethods.keySet(), matches, request);// 如果无法精确匹配, 就会进来这里
}
if (!matches.isEmpty()) {
Comparator<AbstractHandlerMethodMapping<T>.Match> comparator = new AbstractHandlerMethodMapping.MatchComparator(this.getMappingComparator(request));
Collections.sort(matches, comparator);
if (this.logger.isTraceEnabled()) {
this.logger.trace("Found " + matches.size() + " matching mapping(s) for [" + lookupPath + "] : " + matches);
}
AbstractHandlerMethodMapping<T>.Match bestMatch = (AbstractHandlerMethodMapping.Match)matches.get(0);
if (matches.size() > 1) {
AbstractHandlerMethodMapping<T>.Match secondBestMatch = (AbstractHandlerMethodMapping.Match)matches.get(1);
if (comparator.compare(bestMatch, secondBestMatch) == 0) {
Method m1 = bestMatch.handlerMethod.getMethod();
Method m2 = secondBestMatch.handlerMethod.getMethod();
throw new IllegalStateException("Ambiguous handler methods mapped for HTTP path '" + request.getRequestURL() + "': {" + m1 + ", " + m2 + "}");
}
}
this.handleMatch(bestMatch.mapping, lookupPath, request);
return bestMatch.handlerMethod;
} else {
return this.handleNoMatch(this.handlerMethods.keySet(), lookupPath, request);
}
}
public List<String> getMatchingPatterns(String lookupPath) {
List<String> matches = new ArrayList();
Iterator var3 = this.patterns.iterator();
while(var3.hasNext()) {
String pattern = (String)var3.next(); // pattern 是 @RequestMapping 提供的映射
String match = this.getMatchingPattern(pattern, lookupPath); // lookupPath + .* 后能够匹配pattern, 那么就不为空
if (match != null) {
matches.add(match);// 对于有后缀的情况, .* 后
}
}
Collections.sort(matches, this.pathMatcher.getPatternComparator(lookupPath));
return matches;
}
最关键是这里 getMatchingPatterns :
private String getMatchingPattern(String pattern, String lookupPath) {
if (pattern.equals(lookupPath)) {
return pattern;
} else {
if (this.useSuffixPatternMatch) {
if (!this.fileExtensions.isEmpty() && lookupPath.indexOf(46) != -1) {
Iterator var5 = this.fileExtensions.iterator();
while(var5.hasNext()) {
String extension = (String)var5.next();
if (this.pathMatcher.match(pattern + extension, lookupPath)) {
return pattern + extension;
}
}
} else {
boolean hasSuffix = pattern.indexOf(46) != -1;
if (!hasSuffix && this.pathMatcher.match(pattern + ".*", lookupPath)) {
return pattern + ".*"; // 关键是这里
}
}
}
if (this.pathMatcher.match(pattern, lookupPath)) {
return pattern;
} else {
return this.useTrailingSlashMatch && !pattern.endsWith("/") && this.pathMatcher.match(pattern + "/", lookupPath) ? pattern + "/" : null;
}
}
}
而对于AbstractUrlHandlerMapping ,匹配不上就是匹配不上, 不会进行 +.* 后在匹配。
关键方法是这个:
protected Object lookupHandler(String urlPath, HttpServletRequest request) throws Exception {
Object handler = this.handlerMap.get(urlPath);
if (handler != null) {
if (handler instanceof String) {
String handlerName = (String)handler;
handler = this.getApplicationContext().getBean(handlerName);
}
this.validateHandler(handler, request);
return this.buildPathExposingHandler(handler, urlPath, urlPath, (Map)null);
} else {
List<String> matchingPatterns = new ArrayList();
Iterator var5 = this.handlerMap.keySet().iterator();
while(var5.hasNext()) {
String registeredPattern = (String)var5.next();
if (this.getPathMatcher().match(registeredPattern, urlPath)) {
matchingPatterns.add(registeredPattern);
}
}
String bestPatternMatch = null;
Comparator<String> patternComparator = this.getPathMatcher().getPatternComparator(urlPath);
if (!matchingPatterns.isEmpty()) {
Collections.sort(matchingPatterns, patternComparator);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Matching patterns for request [" + urlPath + "] are " + matchingPatterns);
}
bestPatternMatch = (String)matchingPatterns.get(0);
}
if (bestPatternMatch != null) {
handler = this.handlerMap.get(bestPatternMatch);
String pathWithinMapping;
if (handler instanceof String) {
pathWithinMapping = (String)handler;
handler = this.getApplicationContext().getBean(pathWithinMapping);
}
this.validateHandler(handler, request);
pathWithinMapping = this.getPathMatcher().extractPathWithinPattern(bestPatternMatch, urlPath);
Map<String, String> uriTemplateVariables = new LinkedHashMap();
Iterator var9 = matchingPatterns.iterator();
while(var9.hasNext()) {
String matchingPattern = (String)var9.next();
if (patternComparator.compare(bestPatternMatch, matchingPattern) == 0) {
Map<String, String> vars = this.getPathMatcher().extractUriTemplateVariables(matchingPattern, urlPath);
Map<String, String> decodedVars = this.getUrlPathHelper().decodePathVariables(request, vars);
uriTemplateVariables.putAll(decodedVars);
}
}
if (this.logger.isDebugEnabled()) {
this.logger.debug("URI Template variables for request [" + urlPath + "] are " + uriTemplateVariables);
}
return this.buildPathExposingHandler(handler, bestPatternMatch, pathWithinMapping, uriTemplateVariables);
} else {
return null;
}
}
}
当然, 或许我们可以设置自定义的PathMatcher ,从而到达目的。 默认的 是AntPathMatcher 。
来源:https://blog.csdn.net/ruipheng/article/details/65438703


猜你喜欢
- 享元模式(Flyweight Pattern)主要用于减少创建对象的数量,以减少内存占用和提高性能。这种类型的设计模式属于结构型模式,它提供
- 前言我在以往的文章中曾介绍过如何给Word文档添加文本水印和图片水印,及怎样删除文档中的水印。关于文本水印,之前那篇教程里主要指的是单行字体
- 前言一直对它们之间的关系感到好奇,SpringBoot既然是Spring的封装,那么SpringBoot在初始化时应该也会有Bean的加载,
- Android原生控件只有横向进度条一种,而且没法变换样式,比如原生rom的样子很丑是吧,当伟大的产品设计要求更换前背景,甚至纵向,甚至圆弧
- 前言可能对于很多新人来讲,看到这个题目,想到的能接收输入法输入的内容大概只有EditText和TextView这两个控件了,其实不然,只要是
- 定义JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意方法和属性;这种动
- Map映射Map映射是一个java集合存储在键 - 值对的元素,并且不允许在列表中重复的元素。 Map接口提供三种collection视图,
- 普通校验导入依赖:默认的报错:没有提示具体的属性设置自己的错误信息提示:创建 ValidationMessages.properties内容
- 1、获取db实例SQLiteDatabase db=dbhelper.getWritableDatabase();2、Cursord对象获取
- 1.ReadWriteLock介绍为什么我们有了Lock,还要用ReadWriteLock呢。我们对共享资源加锁之后,所有的线程都将会等待。
- 我就废话不多说了,大家还是直接看代码吧~import com.alibaba.fastjson.JSON;import java.util.
- 四舍五入是我们小学的数学问题,这个问题对于我们程序猿来说就类似于1到10的加减乘除那么简单了。在讲解之间我们先看如下一个经典的案
- 引言本文收集了我在看Lucene源码中遇到的所有的对单值(int,long,float,double)的压缩算法,可能一种类型针对不同的场景
- 最近在一本J2EE的书中看到了很不错的对集合框架的说明文章,筛选后发上来和大家共享,集合框架提供管理对象集合的接口和类.它包含接口,类,算法
- 本文介绍了Android 仿微信自定义数字键盘的实现代码,分享给大家,希望对大家有帮助最终效果:实现这个自定义键盘的思路很简单:要写出一个数
- 先看进度条的效果:具体实现:新建类,继承自View,在onDraw中进行绘制:import android.content.Context;
- maven简介及优势 maven是一个项目构建和管理的工具,提供了帮助管理 构建、文档、报告
- 聊一聊kotlin协程“低级”apiKotlin协程已经出来很久了,相信大家都有不同程度的用上了,由
- 前言很多时候,我们定义接口或者调用别人的接口时,手里只有一份接口文档,文档中提供一段示例json格式的报文,我们需要根据json中的字段,挨
- 主要通过System.Resources.ResourceManager类中GetString和GetObject两个方法。两个方法的返回值