spring mvc url匹配禁用后綴訪問操作
spring mvc url匹配禁用后綴訪問
在spring mvc中默認(rèn) 訪問url 加任意后綴名都能訪問
比如:你想訪問 /login ,但是通過 /login.do /login.action /login.json 都能訪問
通常來說可能沒有影響,但對(duì)于權(quán)限控制,這就嚴(yán)重了。
權(quán)限控制通常有兩種思路:
1)弱權(quán)限控制
允許所有url通過,僅對(duì)個(gè)別重要的url做權(quán)限控制。此種方式比較簡(jiǎn)單,不需要對(duì)所有url資源進(jìn)行配置,只配置重要的資源。
2)強(qiáng)權(quán)限控制
默認(rèn)禁止所有url請(qǐng)求通過,僅開放授權(quán)的資源。此種方式對(duì)所有的url資源進(jìn)行控制。在系統(tǒng)種需要整理所有的請(qǐng)求,或者某一目錄下所有的url資源。這種方式安全控制比較嚴(yán)格,操作麻煩,但相對(duì)安全。
如果用第二種方式,則上面spring mvc的訪問策略對(duì)安全沒有影響。
但如果用第一種安全策略,則會(huì)有很大的安全風(fēng)險(xiǎn)。
例如:我們控制了/login 的訪問,但是我們默認(rèn)除/login的資源不受權(quán)限控制約束,那么攻擊者就可以用 /login.do /login.xxx 來訪問我們的資源。
在spring 3.1之后,url找對(duì)應(yīng)方法的處理步驟,第一步,直接調(diào)用RequestMappingHandlerMapping查找到相應(yīng)的處理方法,第二步,調(diào)用RequestMappingHandlerAdapter進(jìn)行處理
我們?cè)赗equestMappingHandlerMapping中可以看到
/** * 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>
在匹配模式時(shí)是否使用后綴模式匹配,默認(rèn)值為true。這樣你想訪問 /login ,通過 /login.* 就不能訪問了。
spring mvc 之 請(qǐng)求url 帶后綴的情況
RequestMappingInfoHandlerMapping 在處理http請(qǐng)求的時(shí)候, 如果 請(qǐng)求url 有后綴,如果找不到精確匹配的那個(gè)@RequestMapping方法。
那么,就把后綴去掉,然后.* 去匹配,這樣,一般都可以匹配。 比如有一個(gè)@RequestMapping("/rest"), 那么精確匹配的情況下, 只會(huì)匹配/rest請(qǐng)求。
但如果我前端發(fā)來一個(gè) /rest.abcdef 這樣的請(qǐng)求, 又沒有配置 @RequestMapping("/rest.abcdef") 這樣映射的情況下, 那么@RequestMapping("/rest") 就會(huì)生效。
原理呢?處理鏈?zhǔn)沁@樣的:
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)
關(guān)鍵是PatternsRequestCondition, 具體來說是這個(gè)方法:
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);// 這里是關(guān)鍵,它去尋找,找到了就找到了,找不到就不會(huì)再去尋找了 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);// 如果能夠精確匹配, 就會(huì)進(jìn)來這里 } if (matches.isEmpty()) { this.addMatchingMappings(this.handlerMethods.keySet(), matches, request);// 如果無法精確匹配, 就會(huì)進(jìn)來這里 } 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);// 對(duì)于有后綴的情況, .* 后 } } Collections.sort(matches, this.pathMatcher.getPatternComparator(lookupPath)); return matches; } 最關(guān)鍵是這里 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 + ".*"; // 關(guān)鍵是這里 } } } if (this.pathMatcher.match(pattern, lookupPath)) { return pattern; } else { return this.useTrailingSlashMatch && !pattern.endsWith("/") && this.pathMatcher.match(pattern + "/", lookupPath) ? pattern + "/" : null; } } }
而對(duì)于AbstractUrlHandlerMapping ,匹配不上就是匹配不上, 不會(huì)進(jìn)行 +.* 后在匹配。
關(guān)鍵方法是這個(gè):
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; } } }
當(dāng)然, 或許我們可以設(shè)置自定義的PathMatcher ,從而到達(dá)目的。 默認(rèn)的 是AntPathMatcher 。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot整合Groovy腳本實(shí)現(xiàn)動(dòng)態(tài)編程詳解
這篇文章主要為大家介紹了SpringBoot整合Groovy腳本實(shí)現(xiàn)動(dòng)態(tài)編程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09Java編程實(shí)現(xiàn)中英混合字符串?dāng)?shù)組按首字母排序的方法
這篇文章主要介紹了Java編程實(shí)現(xiàn)中英混合字符串?dāng)?shù)組按首字母排序的方法,涉及Java字符串操作及拼音轉(zhuǎn)換的相關(guān)使用技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-11-11java ConcurrentHashMap鎖分段技術(shù)及原理詳解
這篇文章主要介紹了java ConcurrentHashMap鎖分段技術(shù)詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07Java使用ScriptEngine動(dòng)態(tài)執(zhí)行代碼(附Java幾種動(dòng)態(tài)執(zhí)行代碼比較)
這篇文章主要介紹了Java使用ScriptEngine動(dòng)態(tài)執(zhí)行代碼,并且分享Java幾種動(dòng)態(tài)執(zhí)行代碼比較,需要的朋友可以參考下2021-04-04java實(shí)現(xiàn)網(wǎng)頁爬蟲的示例講解
下面小編就為大家?guī)硪黄猨ava實(shí)現(xiàn)網(wǎng)頁爬蟲的示例講解。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-08-08JAVA中SSM框架的搭建實(shí)現(xiàn)CRUD的方法
這篇文章主要介紹了JAVA中SSM框架的搭建實(shí)現(xiàn)CRUD的方法,小編把運(yùn)行代碼列了出來,供大家參考。2017-11-11