Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Websocket with Client Certificate

Tags:

java

websocket

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?

like image 398
Alig Avatar asked Apr 21 '26 09:04

Alig


1 Answers

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.

like image 194
Alig Avatar answered Apr 22 '26 23:04

Alig