首页 > 解决方案 > spring boot ant matchers 参数

问题描述

我想授予以下每个 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东西

标签: springspring-bootspring-securityweb-development-server

解决方案


您可以使用RegexRequestMatcher而不是AntPathRequestMatcher

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

AntPathRequestMatcher与参数不匹配,您可以从代码中读取

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将获得请求路径和参数

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();
    }

推荐阅读