首页 > 解决方案 > http.antMatcher("/**") .authorizeRequests().antMatchers("/") 中的antMatcher("/**") 需要什么?

问题描述

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

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

标签: javaspringspring-bootspring-security

解决方案


它们是不同的东西。

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

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

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


推荐阅读