spring mvc url匹配禁用后缀访问操作

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 。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Spring Boot 定制URL匹配规则的方法

    事情的起源:有人问我,说编写了一个/hello访问路径,但是吧,不管是输入/hello还是/hello.html,还是/hello.xxx都能进行访问.当时我还以为他对代码进行处理了,后来发现不是,后来发现这是Spring Boot路由规则.好了,有废话了下,那么看看我们解决上面这个导致的问题. 构建web应用程序时,并不是所有的URL请求都遵循默认的规则.有时,我们希望RESTful URL匹配的时候包含定界符".",这种情况在Spring中可以称之为"定界符定义的格式&q

  • spring mvc路径匹配原则详解

    在Spring MVC中经常要用到拦截器,在配置需要要拦截的路径时经常用到<mvc:mapping/>子标签,其有一个path属性,它就是用来指定需要拦截的路径的.例如: <mvc:interceptor> <mvc:mapping path="/**" /> <bean class="com.i360r.platform.webapp.runtime.view.interceptor.GenericInterceptor"

  • 解决springmvc使用@PathVariable路径匹配问题

    一.问题 今天作毕设的时候,在搭建ssm框架的使用使用springmvc的@PathVariable时出现了一个路径匹配的问题,最后花了点时间解决了. 代码结构: 问题内容: 访问url为: 按照道理说,我应该到jsp的index页面去.最后的结果确实到了index页面,可是由于该页面引用了几个css和js,报异常找不到.有使用过spring经验的童鞋应该知道使用如下代码解决静态资源的访问. // 方法一 <mvc:default-servlet-handler/> // 方法二 <mv

  • 详解SpringMVC的url-pattern配置及原理剖析

    xml里面配置标签: <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> &

  • spring mvc url匹配禁用后缀访问操作

    spring mvc url匹配禁用后缀访问 在spring mvc中默认 访问url 加任意后缀名都能访问 比如:你想访问 /login ,但是通过 /login.do /login.action /login.json 都能访问 通常来说可能没有影响,但对于权限控制,这就严重了. 权限控制通常有两种思路: 1)弱权限控制 允许所有url通过,仅对个别重要的url做权限控制.此种方式比较简单,不需要对所有url资源进行配置,只配置重要的资源. 2)强权限控制 默认禁止所有url请求通过,仅开放

  • Java Spring MVC获取请求数据详解操作

    目录 1. 获得请求参数 2. 获得基本类型参数 3. 获得POJO类型参数 4. 获得数组类型参数 5. 获得集合类型参数 6. 请求数据乱码问题 7. 参数绑定注解 @requestParam 8. 获得Restful风格的参数 9. 自定义类型转换器 1.定义转换器类实现Converter接口 2.在配置文件中声明转换器 3.在<annotation-driven>中引用转换器 10. 获得Servlet相关API 11. 获得请求头 11.1 @RequestHeader 11.2 @

  • Spring MVC url提交参数和获取参数

    普通URL提交参数 该格式url为:url.do?param1=mahc&param2=8888.00 需要在上文中的HelloController对象添加方法如下: /** * Spring MVC URL提交参数 * @param name * @return */ @RequestMapping("/param") public ModelAndView getInfo(@RequestParam("name") String name){ Strin

  • Spring MVC URL地址映射的示例代码

    目录 1.@RequestMapping的介绍 2.映射单个URL 3.映射多个URL 4.映射URL在控制器上 5.@RequestMapping的常用属性 5.1value属性 5.2method属性 5.3params属性 6.小结 1.@RequestMapping的介绍 通过@RequestMapping,我们可以把请求地址和方法进行绑定的,可以在类.方法上进行声明. 类级别的注解负责把一个特定的请求路径映射到一个控制器上,把URL和类绑定 通过方法级别的注解可以细化映射,可以把一个特

  • Maven工程搭建spring boot+spring mvc+JPA的示例

    本文介绍了Maven工程搭建spring boot+spring mvc+JPA的示例,分享给大家,具体如下: 添加Spring boot支持,引入相关包: 1.maven工程,少不了pom.xml,spring boot的引入可参考官网: <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId>

  • Spring根据URL参数进行路由的方法详解

    前言 本文主要介绍了关于Spring根据URL参数进行路由的相关内容,分享出来供大家参考学习价值,下面来一起看看详细的介绍吧. 发现问题 最近在写接口的时候发现一个问题,就是两个REST接口的URL的path部分是一样的,根据query传入不同的参数来区分. 比如S3普通上传接口是是: PUT /{bucketname}/{ objectname} 分块上传的接口是: PUT /{bucketname}/{objectname}?partNumber={partNumber}&uploadId=

  • spring mvc中注解@ModelAttribute的妙用分享

    前言 本文主要给大家介绍了关于spring mvc注解@ModelAttribute妙用的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧. 在Spring mvc中,注解@ModelAttribute是一个非常常用的注解,其功能主要在两方面: 运用在参数上,会将客户端传递过来的参数按名称注入到指定对象中,并且会将这个对象自动加入ModelMap中,便于View层使用: 运用在方法上,会在每一个@RequestMapping标注的方法前执行,如果有返回值,则自动将该返回值

  • 详解快速搭建Spring Boot+Spring MVC

    Spring Boot的出现大大简化了Spring项目的初始搭建和开发过程,今天我们快速搭建一个带有页面渲染(themeleaf模板引擎)的Spring Boot环境. 一.首先我们在IDEA中创建一个Maven项目 勾选create from archetype,选择webapp 二.在pom文件中添加Spring Boot依赖和themeleaf依赖 <dependency> <groupId>org.springframework.boot</groupId> &

  • ASP.NET MVC对URL匹配操作

    1.使用{parameter}做模糊匹配 {parameter}:花括弧加任意长度的字符串,字符串不能定义成controller和action字母.默认的就是模糊匹配. 例如:{admin}. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace MVCURLMatc

随机推荐