1

I'm using spring-boot-starter-security that automatically secures all of my @GetMapping rest endpoints by default.

Question: how can I explicit only whitelist a subpath that should not be secured?

I tried as follows:

@Configuration
public class DocumentsSecurityConfiguration implements WebSecurityConfigurer<WebSecurity> {
    @Override
    public void init(WebSecurity builder) { }

    //should allow unauthenticated access
    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/documents/**");
    }
}

BUT: the localhost:8080/documents root path should remain secured. Only subpaths like /documents/123 should remain open.

Problem: When I now access the root path /documents, it is not secured anymore.

Is my AntMatcher wrong?

membersound
  • 81,582
  • 193
  • 585
  • 1,120

2 Answers2

3

This behavior is an optimization, see AntPathRequestMatcher:

Using a pattern value of /** or ** is treated as a universal match, which will match any request. Patterns which end with /** (and have no other wildcards) are optimized by using a substring match — a pattern of /aaa/** will match /aaa, /aaa/ and any sub-directories, such as /aaa/bbb/ccc.

There are some possible ways to solve your problem:

dur
  • 15,689
  • 25
  • 79
  • 125
0

I guess maybe some thing like this:

@Configuration
@EnableWebSecurity
@Order(SecurityProperties.BASIC_AUTH_ORDER)
@Slf4j
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String[] AUTH_WHITE_LIST = {
        // swagger-ui
          "/v2/api-docs"
        , "/swagger-resources"
        , "/swagger-resources/**"
        , "/configuration/security"
        , "/swagger-ui.html"
        , "/webjars/**"
        , "/security/**"
        // spring actuator
        , "/actuator"
        , "/actuator/**"
    };

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.anonymous().and()
                .authorizeRequests().antMatchers(AUTH_WHITE_LIST).permitAll();
    }
}

And please care about the Order, spring security is based on filers and basically the order is important. If any other matcher reject the request, it will not arrive at this config.

For the problem you mentioned,

I think you have to write a custom filter do deal with it. allow only "/documents" with some additional path, but stop accessing "/documents".

I personally suggest you adjust the url design, maybe change it to "/documents/all" is better than "/documents" in this situation? although it is a bit of against the rest api tutorials on the Internet.

The code come from one of my project, but some unrelative part has been removed. Hope this may help.

Lang
  • 943
  • 13
  • 33