【问题标题】:What is the need for antMatcher("/**") in http.antMatcher("/**") .authorizeRequests().antMatchers("/")? [duplicate]http.antMatcher("/**") .authorizeRequests().antMatchers("/") 中的antMatcher("/**") 需要什么? [复制]
【发布时间】:2020-04-16 11:42:22
【问题描述】:

我正在学习 Spring Security,我从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();
  }

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

【问题讨论】:

    标签: java spring spring-boot spring-security


    【解决方案1】:

    它们是不同的东西。

    • http.antMatcher() 配置哪个 URL 将由这个 SecurityFilterChain 处理。默认是匹配所有 URL。这就是为什么如果你删除 http.antMatcher("/**") 也是一样的原因。

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

    所以如果一个 URL 与 http.antMatcher() 不匹配,Spring security 将不会处理它并且 http.authorizeRequests() 将不适用于这个 URL。也就是说,要让http.authorizeRequests()中配置的URL生效,必须由Spring Security处理并在http.antMatcher()中也匹配。

    【讨论】:

      【解决方案2】:

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

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

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

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

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

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

        匹配任何提供的请求。

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

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

        如您所见,调用antMatcher("/**") 没有任何效果,只是明确记录了安全性应用于所有请求。

      • 第二个调用适用于ExpressionInterceptUrlRegistry 对象,并指定一个“ant”过滤的“rule”。可以定义许多规则,例如在示例中antMatchers(...)anyRequest() 分别启动一个新规则,您可以拥有多个具有不同模式的antMatchers(...) 规则。

        依次检查规则,直到有一个匹配传入的请求。

      主过滤器和规则过滤器必须独立匹配请求,以确保请求得到保护,如规则所指定,例如permitAll()denyAll()authenticated()hasRole("ROLE_FOO")

      【讨论】:

        猜你喜欢
        • 2018-03-27
        • 2019-05-26
        • 2018-04-28
        • 2020-05-24
        • 2016-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-21
        相关资源
        最近更新 更多