Video in progress

Strong Middle 📨 Kafka and messaging

You need to connect to prod Kafka with TLS and SASL/SCRAM. How do you configure that in a Spring Boot application, and where do people usually go wrong?

You set security.protocol=SASL_SSL, sasl.mechanism=SCRAM-SHA-512 and the login through sasl.jaas.config, and give a truststore for TLS. Passwords come from secrets, not from the code; the producer, consumer and admin client must all get the same settings.

📖 Answer

spring:
  kafka:
    bootstrap-servers: kafka-1:9093,kafka-2:9093
    security:
      protocol: SASL_SSL
    ssl:
      trust-store-location: file:/etc/kafka/truststore.p12
      trust-store-password: ${KAFKA_TRUSTSTORE_PASSWORD}
      trust-store-type: PKCS12
    properties:
      sasl.mechanism: SCRAM-SHA-512
      sasl.jaas.config: >-
        org.apache.kafka.common.security.scram.ScramLoginModule required
        username="${KAFKA_USER}" password="${KAFKA_PASSWORD}";

Everything under spring.kafka.properties applies equally to the producer, consumer and admin client, which is exactly what you need for security.

These are the usual places people stumble:

  • A forgotten ; at the end of sasl.jaas.config. The error text says nothing useful; the connection simply doesn't work.
  • Mixed-up ports: on the broker 9092 is PLAINTEXT and 9093 is SASL_SSL. Connecting with TLS to the wrong port gives "handshake failed" or a strange timeout.
  • Hostname verification: if the certificate doesn't contain the broker's DNS name, the connection is rejected. Turning it off with ssl.endpoint.identification.algorithm= (empty) looks like a quick fix, but it removes MITM protection; fix the certificate instead.
  • Missing ACLs: authentication passes, but you get a TopicAuthorizationException or GroupAuthorizationException. A consumer needs Read on the topic and also Read on the group, and people often forget the second.

mTLS is an alternative to SCRAM: login happens through the certificate and a keystore is added. In cloud-hosted Kafka, OAuth (OAUTHBEARER) is often used.