我有一个简单的应用程序做相互TLS。实际上,在运行应用程序时,一切都按照我的预期运行。
然而,以下测试不起作用,我想理解为什么,因为它似乎进入安全链但信任库配置似乎完全被忽略。
@ActiveProfiles("test")
@RunWith(SpringRunner.class)
@ContextConfiguration
@WebMvcTest
public class ConfigurationTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private WebApplicationContext context;
@Before
public void setup() {
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
public void untrustedClientShouldBeForbidden() throws Exception {
this.mockMvc.perform(get("/v1/load")
.with(x509(getCertificateFromFile("src/test/resources/untrusted-cert.pem")))
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.content("{\"foo\":\"bar\"}"))
.andDo(print())
.andExpect(status().is(HttpStatus.FORBIDDEN.value()));
}
我的安全配置非常简单,如下:
@Override
protected void configure(HttpSecurity http) throws Exception {
//disable crsf and sessions for this web app
http.httpBasic().disable().csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and().x509()
.subjectPrincipalRegex("CN=(.*?)(?:,|$)")
.userDetailsService(userDetailsService());
}
我的测试配置(在进行手动测试时有效)看起来像这样(application-test.properties):
server.ssl.trust-store=src/test/resources/test.truststore
server.ssl.trust-store-password=changeit
server.ssl.key-store-provider=SUN
server.ssl.key-store-type=JKS
编辑:重命名单元测试功能,以更好地传达测试的意图。
原来我的测试类没有正确注释。
在我的主配置类中,我更改了:
@SpringBootApplication
@PropertySources({
@PropertySource("classpath:application.properties"),
@PropertySource("classpath:application-${spring.profiles.active}.properties")})
@ComponentScan("foo.bar.blah")
public class Application {
至:
@SpringBootApplication(scanBasePackages="foo.bar.blah")
@PropertySources({
@PropertySource("classpath:application.properties"),
@PropertySource("classpath:application-${spring.profiles.active}.properties")})
public class Application {
在我的测试类中,我停止使用@MockWebMvc来支持这种配置:
@ActiveProfiles("test")
@RunWith(SpringRunner.class)
@ContextConfiguration
@SpringBootTest
@AutoConfigureMockMvc
public class ConfigurationTest {
现在正确地拾取配置,并且单元测试的所有操作都符合我的预期。