在我的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());
}
}
在App中的配置如下:
@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(),则测试成功或失败取决于凭据放置的好坏。 但是,如果直接调用restTemplate而不使用BasicAuth,则允许所有请求(因此我的测试断言失败)。
作为具有完整配置的IT测试,我希望身份验证是强制性的,为什么情况并非如此?
答案 0 :(得分:0)
[编辑]我的第一个解决方案是错误的,正确的配置是:
@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 / **)。