spring-projects / spring-security

Spring Security
http://spring.io/projects/spring-security
Apache License 2.0
8.71k stars 5.87k forks source link

Endpoints with path variables match incorrectly with the MvcRequestMatcher #15501

Open npriebe opened 1 month ago

npriebe commented 1 month ago

Describe the bug I have two endpoints with path variables. One endpoint is specified with two path variables and the other with one path variable. I want to open the endpoint with two path variables via the MvcRequestMatcher. But when I do this, the other endpoint with one path variable is also opened.

In my case I use Spring-Security v5.6.1

RestController:

@RestController
public class TestController
{
    /**
     * Secured endpoint by {@link SecurityConfiguration}
     */
    @GetMapping("{username}/secured")
    public String getSecuredEndpoint(@PathVariable String username)
    {
        return username;
    }

    /**
     * Open endpoint by {@link SecurityConfiguration}
     */
    @GetMapping("{firstname}/{lastname}")
    public String getOpenEndpoints(@PathVariable String firstname, @PathVariable String lastname)
    {
        return firstname + " " + lastname;
    }
}

SecurityConfiguration

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter
{
    @Autowired
    private HandlerMappingIntrospector handlerMappingIntrospector;

    @Override
    public void configure(HttpSecurity http) throws Exception
    {
        var mvcMatcher = new MvcRequestMatcher(handlerMappingIntrospector, "/{firstname}/{lastname}");
        mvcMatcher.setMethod(HttpMethod.GET);

        http.authorizeRequests()
                .requestMatchers(mvcMatcher)
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .csrf()
                .ignoringRequestMatchers(mvcMatcher);
    }
}

If I omit the suffix secured from the secured endpoint, the matching works properly.

It seems as if it cannot correctly assign the endpoint for the MvcRequestMatcher when resolving the path variables.

To Reproduce The problem can be simulated with the code examples given above.

Expected behavior Only the endpoint specified via the MvcRequestMatcher may match.

Sample Repository: https://github.com/npriebe/mvc-path-variable-matching

sdaus commented 3 weeks ago

Hi, is there any update on this? I'm also experiencing this problem.