Connecting to Cassandra from Spring Boot application using SSL / TLS

Connecting to Cassandra from Spring Boot application using SSL / TLS

When you setup a remote cassandra cluster, and you want to communicate with it from your spring boot application, you have to make sure that all data which are transferred between your application and cluster are encrypted.

It took me a while to figure out how to do that.

First, you need to generate SSL / TLS certificate and setup cassandra to use SSL / TLS communication only. You will find pleny or other blog posts how to do that, so I'm not going to mention it here.

When you have your spring boot app, you probably have a class, which configures the Cassandra connection.

@Configuration
public class CassandraConfiguration {
    ...
}

There is usually something like this:

        Cluster.Builder builder = Cluster.builder()
            .withClusterName(properties.getClusterName())
            .withProtocolVersion(protocolVersion)
            .withPort(getPort(properties));

The main trick is, to add:

            builder.withSSL(createSslOptions());

    private SSLOptions createSslOptions() {
        return JdkSSLOptions.builder()
            .withSSLContext(createSslContextWithTruststore())
            .withCipherSuites(CIPHERS)
            .build();
    }

    private SSLContext createSslContextWithTruststore()  {
        try {
            return new SSLContextBuilder()
                .loadTrustMaterial(new File(trustoreFilename), truststorePassword.toCharArray())
                .build();
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException | CertificateException | IOException e) {
            throw new SecurityException("Could not create SSL context", e);
        }
    }

truststore file, is the file which contains client certificate (you just need to add this certificate into the truststore using java keytool utility).

keytool -importcert -v -trustcacerts -alias "CLIENT" -file CLIENT.cer.pem \
-keystore client.truststore -noprompt

Related Posts