You know from previous post that SecurityFilterChain determines which requests go through the filter chain, so how does SecurityFilterChain match to a specific request?

How to intercept specific requests

Only requests that satisfy the match method of a SecurityFilterChain can be processed by that SecurityFilterChain, so how do you configure a SecurityFilterChain to process a specific path?

RequestMatcher

HttpSecurity has a built-in RequestMatcher property to handle path matching. The RequestMatcher can be summarized in the following categories.

RequestMatcher

Use the Ant path.

1
httpSecurity.antMatcher("/foo/**");

If you configure a global Servlet Path such as /v1, configure the ant path as /v1/foo/** to be consistent with the MVC style.

1
httpSecurity.mvcMatcher("/foo/**");

Also MVC style can automatically match suffixes, for example /foo/hello can match /foo/hello.do, /foo/hello.action and so on. Alternatively you can use regular expressions for path matching.

1
httpSecurity.regexMatcher("/foo/.+");

If the above doesn’t meet your needs, you can customize the matching rules with the HttpSecurity.requestMatcher method; if you want to match multiple rules, you can freely combine the matching rules with the HttpSecurity.requestMatchers method, like this.

1
2
3
httpSecurity.requestMatchers(requestMatchers ->
requestMatchers.mvcMatchers("/foo/**")
.antMatchers("/admin/*get"));

Once you configure the path matching rule, you will find that the default form login 404 is not accessible because the default is /login, which you can’t access after adding the prefix.

Usage Scenarios

For example, if your backend management system and frontend application each take a different filter chain, you can configure the respective filter chain based on the access path. For example.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
    * Admin 过滤器链.
    *
    * @param http the http
    * @return the security filter chain
    * @throws Exception the exception
    */
@Bean
SecurityFilterChain adminSecurityFilterChain(HttpSecurity http) throws Exception {
    http.requestMatchers(requestMatchers -> requestMatchers.mvcMatchers("/admin/**"))
        //todo 其它配置
    return http.build();
}

/**
    * App 过滤器链.
    *
    * @param http the http
    * @return the security filter chain
    * @throws Exception the exception
    */
@Bean
SecurityFilterChain appSecurityFilterChain(HttpSecurity http) throws Exception {
    http.requestMatchers(requestMatchers -> requestMatchers.mvcMatchers("/app/**"));
    //todo 其它配置
    return http.build();
}

Also use this feature to reduce coupling between different rule URIs.

Think about how HttpSecurity, a Spring bean, can be reused.

Reference https://mp.weixin.qq.com/s/W_N-il-IIFaXI7_YZp1zFQ