Spring security application of antMatcher() vs. antMatchers()

Ole :

Just want to see whether I'm interpreting the answer to this question the right way.

If we only need to secure one path like this:

http.antMatcher("/api/**").authorizeRequests()....

Then use antMatcher().

If we need to secure multiple URL paths like this:

http
.authorizeRequests()
    .antMatchers("/high_level_url_A/sub_level_1").hasRole('USER')
    .antMatchers("/high_level_url_A/sub_level_2").hasRole('USER2')
    ...

Then use antMatchers().

There are two answers in this question, but the example provided in each of them contradicts example given in the other. The first answer says that the author does not need antMatcher() and the second says to always start with `antMatcher() IIUC.

dsep :

HttpSecurity.antMatcher() changes the default request matcher for the HttpSecurity instance to an AntPathRequestMatcher from AnyRequestMatcher. ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry.antMatchers() is used for applying authorization rules to a subset of endpoints associated with the current HttpSecurity instance.

Example code:

http
    .antMatcher("/api/**")
    .httpBasic()
        .disable()
    .authorizeRequests()
        .antMatchers("/api/user/**", "/api/ticket/**", "/index")
            .hasRole("ROLE_USER");

In the example above, basic authorization is disabled for all endpoints matching /api/**. Additionally, endpoints matching /api/user/** or /api/ticket/** will require the request's Authentication to contain ROLE_USER. However, when a user attempts to access /index, they will be met with a basic auth prompt. Upon entering credentials, the user will be granted access to the endpoint regardless of whether or not the request's Authentication contains ROLE_USER. This is because .antMatcher("/api/**") is limiting the scope of the entire HttpSecurity instance to that specific AntMatcher.

The example below would ensure that the HttpSecurity's scope includes the three previous AntMatchers and nothing else:

http
    .requestMatchers()
        .antMatchers("/api/user/**", "/api/ticket/**", "/index")
        .and()
    .httpBasic()
        .disable()
    .authorizeRequests()
        .any()
            .hasRole("ROLE_USER");

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=476027&siteId=1