I have a Java websocket client using the javax.websocket libraries which currently looks like this:
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.setDefaultMaxTextMessageBufferSize(BUFFER_SIZE);
container.connectToServer(this, ENDPOINT_URI);
Now I have the requirement, that the client needs to supply a client certificate to the server. How can this be accomplished?
I found a solution, so I answer my own question:
The WebsocketContainer can be configured with an ClientEndpointConfig. This allows to set a custom SSLContext. Then client certificate must be attached to the SSLContext. Code:
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.setDefaultMaxTextMessageBufferSize(BUFFER_SIZE);
container.connectToServer(new PojoEndpointClient(this, new ArrayList<>()), createClientConfig(), endpointURI);
And the ClientEndpointConfig can be constructed like this:
private ClientEndpointConfig createClientConfig() throws KeyManagementException, UnrecoverableKeyException,
NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
ClientEndpointConfig.Builder builder = ClientEndpointConfig.Builder.create();
ClientEndpointConfig config = builder.decoders(new ArrayList<>()).encoders(new ArrayList<>())
.preferredSubprotocols(new ArrayList<>()).build();
SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(clientCert.toFile(), clientCertPassword,
clientCertPassword, (aliases, socket) -> aliases.keySet().iterator().next()).build();
config.getUserProperties().put(Constants.SSL_CONTEXT_PROPERTY, sslContext);
return config;
}
This will present the client certificate to the server when establishing the websocket connection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With