http.antMatcher("/**") .authorizeRequests().antMatchers("/") 中的 antMatcher("/**") 需要什么?

Arj*_*jun 3 java spring spring-security spring-boot

我正在学习 spring 安全,我从https://spring.io/guides/tutorials/spring-boot-oauth2/ 中发现了这段代码

 @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .antMatcher("/**")
      .authorizeRequests()
        .antMatchers("/", "/login**", "/webjars/**", "/error**")
        .permitAll()
      .anyRequest()
        .authenticated();
  }
Run Code Online (Sandbox Code Playgroud)

我删除.antMatcher("/**")了,代码仍然有效。我知道**匹配路径中的零个或多个目录,所以我认为antMatcher("/**").authorizeRequestes().antMatcher("/login")"/login"直接或间接匹配根路径下的目录,即我希望它匹配路径/login/demo/login但事实并非如此,它只匹配/login根路径正下方的目录。那么究竟需要.antMatcher("/**") here什么呢?

Ken*_*han 7

它们是不同的东西。

  • http.antMatcher()配置将由 this 处理的 URL SecurityFilterChain。默认是匹配所有 URL。这就是为什么如果您删除http.antMatcher("/**").

  • http.authorizeRequests() 为 URL 配置授权事项,例如是否需要进行身份验证或是否只有某些角色可以访问它等。

因此,如果某个 URL 与 不匹配http.antMatcher(),Spring 安全性将不会处理它并且http.authorizeRequests()不会应用于此 URL。换句话说,为了让配置的 URLhttp.authorizeRequests()生效,它应该由 Spring Security 处理并匹配http.antMatcher()


And*_*eas 5

请注意,第一个是单数antMatcher,第二个是复数antMatchers,并且示例中的缩进方式不同。

实际上,问题中的示例缩进不正确。正确的缩进是:

@Override
protected void configure(HttpSecurity http) throws Exception {
  http
    .antMatcher("/**")
    .authorizeRequests()
      .antMatchers("/", "/login**", "/webjars/**", "/error**")
        .permitAll()
      .anyRequest()
        .authenticated();
}
Run Code Online (Sandbox Code Playgroud)

那是因为它们适用于两个完全不同的对象:

  • 第一次调用适用于HttpSecurity对象,并指定一个过滤器,甚至在考虑安全性之前应用该过滤器。

    默认的主过滤器是AnyRequestMatcher,javadoc 说:

    匹配任何提供的请求。

    当您调用 时antMatcher("/**"),您AntPathRequestMatcherusing 模式替换该过滤器/**,并且 javadoc 说:

    使用/**或的模式值**被视为通用匹配,它将匹配任何请求。

    如您所见,调用antMatcher("/**")没有任何影响,除了明确记录安全性应用于所有请求之外。

  • 第二个调用适用于一个ExpressionInterceptUrlRegistry对象,并指定一个“蚂蚁”过滤的“规则”。可以定义许多规则,例如在示例中antMatchers(...)anyRequest()每个规则都开始一个新规则,并且您可以拥有多个antMatchers(...)具有不同模式的规则。

    规则按顺序检查,直到与传入请求匹配为止。

主过滤器和规则过滤器必须独立地匹配所述请求,以使请求被固定,如通过规则,例如指定permitAll()denyAll()authenticated()hasRole("ROLE_FOO"),等。