'MockServer How to implement a JUnit mutual TLS authentication?

My SpringBoot application is connecting to third parties servers using a third librabry/framework. One of these remote servers (not yet available) will require mutual TLS (https) connection. My code will provideth P12 and password to the framework in order to connect to this remote server. I need to test this part with Junit integration Test.

MockServer (from www.mock-server.com) is already used for our Junit IT but not yet for mutual TLS authentication and, as a newby, I'm quit confused on how to implement this. Form the doc (https://www.mock-server.com/mock_server/HTTPS_TLS.html) I added in my Junit test the following configuration :

@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…
}

But nothing works, I'm missing some code in my test
In log I can see for i.e :

"MockServerEventLog - no tls for connection"

I cannot find any clear and simple tutorial for this use case. Any help would be greatfull.

So how to implement a full Junit integration test using a Mockserver with mutual TLS authentication ?



Solution 1:[1]

Was having this issue, I added .withSecure(true) when creating expectations.

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jasper