如何为相互TLS身份验证实现JUnit测试?

neskvpey  于 2022-11-11  发布在  其他
关注(0)|答案(1)|浏览(120)

我的Sping Boot 应用程序正在使用第三方库/框架连接到第三方服务器。
这些远程服务器中的一个(还不可用)将需要相互TLS(HTTPS)连接。我的代码将向框架提供P12和密码,以便连接到这个远程服务器。我需要使用JUnit集成测试来测试这个部分。
MockServer已经用于我们的JUnit IT,但还没有用于相互TLS身份验证,作为一个纽比,我对如何实现这一点感到非常困惑。
从我在JUnit中添加的doc测试以下配置:

@BeforeAll
public static void initServer(){

  // ensure https will use SSL context defined by MockServer to allow
  // dynamically generated certificates to be accepted
  HttpsURLConnection.setDefaultSSLSocketFactory(new KeyStoreFactory(new 
  MockServerLogger()).sslContext().getSocketFactory());

  File certif = ResourceUtils.getFile("classpath:mtls/test-cert.crt");
  ConfigurationProperties.tlsMutualAuthenticationCertificateChain(certif.getPath());
  ConfigurationProperties.tlsMutualAuthenticationRequired(true);

  mockServer = ClientAndServer.startClientAndServer(80,443);

  etc…
}

但是没有任何效果,我在测试中丢失了一些代码?
在日志中,我可以看到:
MockServerEventLog -没有用于连接的TLS
我找不到任何清晰和简单的教程为这个用例。任何帮助将是伟大的。
那么,如何使用具有相互TLS身份验证的MockServer来实现完整的JUnit集成测试呢?

nkkqxpd9

nkkqxpd91#

有这个问题,我在创建期望时添加了.withSecure(true)

@Test
public void myTest() {
    mockServer
        .withSecure(true)
        .when(request()
            .withPath("/test"))
        .respond(response()
            .withBody("hello world"));
}

相关问题