Abderrahmane BECHIKH
Abderrahmane BECHIKH

Reputation: 653

spring boot ant matchers parameters

I want to give permission to every of these URLs:

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

I have this two URLs:

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

If URL is typed and has "tata" as parameter i want to access only with the role "tata" and the same thing with "toto"

Upvotes: 4

Views: 6512

Answers (1)

Chao Luo
Chao Luo

Reputation: 2696

You can use RegexRequestMatcher instead of AntPathRequestMatcher

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

AntPathRequestMatcher does not match the params,as you can read from the 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 will get the request path and 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();
    }

Upvotes: 3

Related Questions