Reputation: 334
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?
Upvotes: 3
Views: 6426
Reputation: 334
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.
Upvotes: 4
Reputation: 11251
I am not sure what certificate you are talking about, but probably you mean SSL/TLS certificate. In this case you need just to use wss client(eg nv-websocket-client), which will handle all ssl/tls under the hood.
See also answer: minimal java8 nio secure websocket client (wss)
Upvotes: 0