在spring security中使用requestMatchers().antMatchers()而没有动词的原因是什么?

nuc*_*tus 8 spring-security

Spring安全性oauth实现中有一种常见的做法是使用以下行保护oauth端点:

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

整个设置如下所示:

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

有人可以解释为什么需要特定的行,因为下一行明确表示所有请求都必须经过身份验证吗?

dir*_*rkt 5

requestMatchers行指定安全检查适用于哪些请求。该authorizeRequests行进行实际的安全检查。

如果您省略该requestMatchers行,则所有请求都将按照authorizeRequests指定的方式进行检查。如果没有对某些请求进行检查,则默认情况下检查会成功。

使用该requestMatchers行,不匹配的请求将被其他剩余链检查。


gav*_*koa 3

Spring Security 管理多个 Servlet 过滤器链。

WebSecurityConfigurerAdapter在现代 Spring 安全性(v3.2.x 及更高版本)中,每个链都根据类注释进行配置和应用@Order(...),直到第一次报告它支持HttpServletRequest,这是通过.requestMatchers()DSL 配置的:

从版本 3.1 开始,{@code FilterChainProxy} 使用一系列 {@link SecurityFilterChain} 实例进行配置,每个实例都包含一个 {@link RequestMatcher} 和一个应用于匹配请求的过滤器列表。大多数应用程序仅包含一个过滤器链,如果您使用命名空间,则不必显式设置链。如果您需要更细粒度的控制,可以使用 {@code } 命名空间元素。这定义了 URI 模式和过滤器列表(以逗号分隔的 bean 名称),这些过滤器应应用于与该模式匹配的请求。示例配置可能如下所示:

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;
}
Run Code Online (Sandbox Code Playgroud)

然后选择应用于安全请求的链。

您的设置仅应用于 3 个 URL,如果未进行其他配置,则所有其他 URL 均不安全。