sping boot ant matchers参数

时间:2018-12-11 14:20:07

标签: spring-boot java-ee spring-security web-development-server

我想授予以下所有URL的权限:

.antMatchers("/myPage?param1=tata*").hasRole("tata")
.antMatchers("/myPage?param1=toto*").hasRole("toto")

我有这两个网址:

http://localhost:3000/myPage?param1=tata&param2=0001
http://localhost:3000/myPage?param1=toto&param2=0001

如果键入URL并使用“ tata”作为参数,则我只希望使用角色“ tata”和使用“ toto”来访问

1 个答案:

答案 0 :(得分:0)

您可以使用RegexRequestMatcher代替AntPathRequestMatcher

http
    .authorizeRequests()
         .regexMatchers("\/myPage\?param1=tata(&.*|$)"). hasRole('tata')
         .regexMatchers("\/myPage\?param1=toto(&.*|$)"). hasRole('toto')

AntPathRequestMatcher 不匹配,正如您可以从code

中看到的那样
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;
    }

RegexRequestMatcher将获得请求路径和params

public boolean matches(HttpServletRequest request) {
        if (httpMethod != null && request.getMethod() != null
                && httpMethod != valueOf(request.getMethod())) {
            return false;
        }

        String url = request.getServletPath();
        String pathInfo = request.getPathInfo();
        String query = request.getQueryString();

        if (pathInfo != null || query != null) {
            StringBuilder sb = new StringBuilder(url);

            if (pathInfo != null) {
                sb.append(pathInfo);
            }

            if (query != null) {
                sb.append('?').append(query);
            }
            url = sb.toString();
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Checking match of request : '" + url + "'; against '" + pattern
                    + "'");
        }

        return pattern.matcher(url).matches();
    }