为什么 TestRestTemplate 允许在 Spring Boot IT 测试中进行未经身份验证的请求?

Why TestRestTemplate allow unauthenticated resquest in SpringBoot IT tests?

在我的 springBoot (RELEASE 1.5.20) 应用程序中,启用了基本身份验证。 我使用以下代码创建了完整的 IT 测试

@RunWith(SpringRunner.class)
@ActiveProfiles(profiles = "securedIT")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MYtestIT{
@LocalServerPort
     private int port;

   private String getRootUrl() {
        return "http://localhost:" + port;
   }

   @Autowired
   private TestRestTemplate restTemplate;

    @Test
    public void testAdmincachWitheWrongAuthentication() {
        String baseUri = getRootUrl() + CONTEXT_ROOT;
         HttpEntity<String> entity = new HttpEntity<>(null,  new HttpHeaders());
         URI url = URI.create(baseUri + "/ref/cache/task");

       ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.DELETE, entity, String.class);
       //ResponseEntity<String> response = restTemplate.withBasicAuth("user", "myPwd").exchange(url, HttpMethod.DELETE, entity, String.class);

     assertEquals(ReferenceWSIT.MSG_WRON_STATUS,401, response.getStatusCode().value());
    }
}

在应用程序中的配置是这样的:

@Configuration
public class GlobalWebSecurityConfigurerAdapter extends 
WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
            .antMatchers("ref/v1/**").permitAll()
            .antMatchers("ref/cache/**").authenticated().and().httpBasic();
    }   
}

当我 运行 应用程序时,身份验证过滤器工作正常,当我 运行 Junit 集成测试时出现问题。 如果我调用 restTemplate.withBasicAuth() 测试失败或成功取决于正确或错误的凭据放置。 但是,如果不使用 BasicAuth 直接调用 restTemplate,则允许所有请求(因此我的测试断言失败)。

作为对我的完整配置的 IT 测试,我希望身份验证是强制性的,为什么不是这样?

[编辑]我的第一个解决方案是错误的,正确的配置是:

@Configuration
public class GlobalWebSecurityConfigurerAdapter extends 
WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
            http.csrf().disable()
                .anonymous().disable()
                //following will disable cookie session to force the browser to Authenticate on each request      
               .sessionManagement()
               .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
               .and()
               .authorizeRequests()
               .antMatchers("/ref/cache/**")
               .authenticated().and().httpBasic()
               .and()
               .addFilterAfter(new HmacSecurityFilter(), BasicAuthenticationFilter.class)
               ;
    }   
}

第一个错误:antMatcher 必须以“/”开头:"/ref/cache/**" 而不是 "ref/cache/**"

其次,在我的第二个过滤器 (HmacSecurityFilter) 中,我检查了任何请求(之前是 .antMatchers("ref/v1/**").permitAll() ),并且我做了一个自定义代码以避免检查经过身份验证的 uri (/ref/cache/**) 。