What is the reason to use requestMatchers().antMat

2020-07-06 08:33发布

There is a common practice in the Spring security oauth implementation to secure the oauth endpoints with the following line:

.requestMatchers().antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access")

The entire setup looks like this:

http
  .formLogin().loginPage("/login").permitAll()
  .and()
  .requestMatchers().antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access")
  .and()
  .authorizeRequests().anyRequest().authenticated();

Can someone explain me why that specific line is needed, since the next line explicitly says that all the requests have to be authenticated?

2条回答
迷人小祖宗
2楼-- · 2020-07-06 09:09

Spring Security manages several Servlet filter's chains.

In modern Spring security (v3.2.x and above) each chain configured by WebSecurityConfigurerAdapter and applied based on @Order(...) class annotations until first reported that it supports HttpServletRequest, which is configured via .requestMatchers() DSL:

As of version 3.1, {@code FilterChainProxy} is configured using a list of {@link SecurityFilterChain} instances, each of which contains a {@link RequestMatcher} and a list of filters which should be applied to matching requests. Most applications will only contain a single filter chain, and if you are using the namespace, you don't have to set the chains explicitly. If you require finer-grained control, you can make use of the {@code } namespace element. This defines a URI pattern and the list of filters (as comma-separated bean names) which should be applied to requests which match the pattern. An example configuration might look like this:

public class FilterChainProxy extends GenericFilterBean {
...
/**
 * Returns the first filter chain matching the supplied URL.
 *
 * @param request the request to match
 * @return an ordered array of Filters defining the filter chain
 */
private List<Filter> getFilters(HttpServletRequest request) {
    for (SecurityFilterChain chain : filterChains) {
        if (chain.matches(request)) {
            return chain.getFilters();
        }
    }

    return null;
}

Then selected chain applied to secure request.

Your setting only applied to 3 URLs leaving all other URLs unsecured if otherwise isn't configured.

查看更多
一夜七次
3楼-- · 2020-07-06 09:13

The requestMatchers line specifies to which requests the security check applies. The authorizeRequests line does the actual security check.

If you leave out the requestMatchers line, all requests will get checked in the way authorizeRequests specifies. If there are no checks for some requests, checking will succeed by default.

With the requestMatchers line, requests that don't match will get checked by the other remaining chains.

查看更多
登录 后发表回答