Kafka security: authentication, encryption and ACLs

An unsecured Kafka cluster lets anyone who can reach it read, write and delete any topic. This page explains the three layers of Kafka security, then runs a secured broker inside each program to show SASL and SCRAM logins, TLS with client certificates, and ACLs that allow and deny, including the errors clients get when they are refused.

Share

Contents

The three layers of Kafka security

By default a Kafka listener uses PLAINTEXT: no encryption, no login, and no permission checks. Securing a cluster means adding three separate things, each configured per listener on the broker and matched by settings on every client:

  • Encryption: TLS on the connection, so that nobody on the network can read or change records. The broker presents a certificate, and the client checks it against a truststore.
  • Authentication: the broker learns who the client is. Either the client presents its own TLS certificate (mutual TLS), or it logs in with SASL. The result is a principal such as User:alice.
  • Authorization: for every request, an authorizer checks whether the principal may perform the operation on the resource, using access control lists (ACLs). In KRaft clusters this is the StandardAuthorizer, which keeps the ACLs in the metadata log.

A listener's security.protocol combines the first two: SSL is TLS with optional client certificates, SASL_PLAINTEXT is SASL without encryption, and SASL_SSL is SASL inside TLS, the usual production choice.

Kafka authentication mechanisms
MechanismSinceCredentials kept inBest for
TLS client certificates0.9Your certificate authorityServices that already have a PKI
SASL/GSSAPI (Kerberos)0.9Kerberos KDC, Active DirectoryCompanies that run Kerberos
SASL/PLAIN0.10.0A JAAS file, or a custom callback handlerSimple setups, always over TLS
SASL/SCRAM-SHA-256 and -5120.10.2Salted hashes in the cluster metadataUsername and password users managed by the Admin API
SASL/OAUTHBEARER2.0; OIDC in 3.1An OAuth identity providerShort-lived tokens from a central identity service

The programs start a one-node KRaft cluster in the JVM with KafkaClusterTestKit, the Kafka 4.2.2 test cluster that spring-kafka-test's EmbeddedKafkaKraftBroker is built on, configured with SASL or TLS and the StandardAuthorizer. A real cluster has 3 or more brokers. Three things could not run here and are shown from the Kafka documentation only: Kerberos, which needs a KDC; OAUTHBEARER, which needs an identity provider; and a certificate authority, since the TLS program uses self-signed certificates made with keytool. The SASL programs use SASL_PLAINTEXT to keep them short; production uses SASL_SSL.

SASL logins and ACLs

The broker below accepts three PLAIN users. admin is a super user, which bypasses ACLs; alice may write to orders; bob may read it with the group billing. Every other request is refused, because allow.everyone.if.no.acl.found is false:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.KafkaException;
import org.apache.kafka.common.acl.AccessControlEntry;
import org.apache.kafka.common.acl.AclBinding;
import org.apache.kafka.common.acl.AclBindingFilter;
import org.apache.kafka.common.acl.AclOperation;
import org.apache.kafka.common.acl.AclPermissionType;
import org.apache.kafka.common.resource.PatternType;
import org.apache.kafka.common.resource.ResourcePattern;
import org.apache.kafka.common.resource.ResourceType;
import org.apache.kafka.common.security.auth.SecurityProtocol;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.common.test.KafkaClusterTestKit;
import org.apache.kafka.common.test.TestKitNodes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SaslAndAcls {

    public static void main(String[] args) throws Exception {
        KafkaClusterTestKit cluster = startCluster();
        String bootstrap = cluster.bootstrapServers();
        try (Admin admin = Admin.create(client(bootstrap, "PLAIN", "admin", "admin-secret"))) {
            admin.createTopics(List.of(new NewTopic("orders", 1, (short) 1))).all().get();
            admin.createAcls(List.of(
                    allow("User:alice", ResourceType.TOPIC, "orders", AclOperation.WRITE),
                    allow("User:bob", ResourceType.TOPIC, "orders", AclOperation.READ),
                    allow("User:bob", ResourceType.GROUP, "billing", AclOperation.READ)))
                    .all().get();
            Thread.sleep(500); // ACLs reach the broker through the metadata log
            admin.describeAcls(AclBindingFilter.ANY).values().get().stream()
                    .map(b -> b.entry().principal() + " " + b.entry().permissionType() + " "
                            + b.entry().operation() + " on " + b.pattern().resourceType() + " "
                            + b.pattern().name())
                    .sorted()
                    .forEach(acl -> System.out.println("ACL " + acl));
        }

        attempt("alice sends to orders", () -> send(bootstrap, "alice", "alice-secret"));
        attempt("bob sends to orders", () -> send(bootstrap, "bob", "bob-secret"));
        attempt("bob reads orders as group billing", () -> read(bootstrap, "billing"));
        attempt("bob reads orders as group audit", () -> read(bootstrap, "audit"));
        attempt("bob with a wrong password", () -> send(bootstrap, "bob", "guess"));
        attempt("alice lists topics", () -> {
            try (Admin admin = Admin.create(client(bootstrap, "PLAIN", "alice",
                    "alice-secret"))) {
                return admin.listTopics().names().get().toString();
            }
        });
        cluster.close();
    }

    static AclBinding allow(String principal, ResourceType type, String name,
            AclOperation operation) {
        return new AclBinding(new ResourcePattern(type, name, PatternType.LITERAL),
                new AccessControlEntry(principal, "*", operation, AclPermissionType.ALLOW));
    }

    static String send(String bootstrap, String user, String password) throws Exception {
        try (KafkaProducer<String, String> producer = new KafkaProducer<>(
                client(bootstrap, "PLAIN", user, password),
                new StringSerializer(), new StringSerializer())) {
            var meta = producer.send(new ProducerRecord<>("orders", "order from " + user)).get();
            return "written at offset " + meta.offset();
        }
    }

    static String read(String bootstrap, String group) {
        Map<String, Object> props = client(bootstrap, "PLAIN", "bob", "bob-secret");
        props.put("group.id", group);
        props.put("auto.offset.reset", "earliest");
        try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props,
                new StringDeserializer(), new StringDeserializer())) {
            consumer.subscribe(List.of("orders"));
            for (int i = 0; i < 20; i++) {
                var records = consumer.poll(Duration.ofMillis(500));
                if (!records.isEmpty()) {
                    return "read \"" + records.iterator().next().value() + "\"";
                }
            }
            return "nothing read";
        }
    }

    interface Action {
        String run() throws Exception;
    }

    static void attempt(String label, Action action) {
        try {
            System.out.println(label + ": " + action.run());
        } catch (ExecutionException | KafkaException e) {
            Throwable cause = e instanceof ExecutionException ? e.getCause() : e;
            System.out.println(label + ": " + cause.getClass().getSimpleName() + ": "
                    + cause.getMessage());
        } catch (Exception e) {
            System.out.println(label + ": " + e);
        }
    }

    // Client settings for SASL over plaintext; production uses SASL_SSL
    static Map<String, Object> client(String bootstrap, String mechanism, String user,
            String password) {
        String module = mechanism.equals("PLAIN")
                ? "org.apache.kafka.common.security.plain.PlainLoginModule"
                : "org.apache.kafka.common.security.scram.ScramLoginModule";
        Map<String, Object> props = new HashMap<>();
        props.put("bootstrap.servers", bootstrap);
        props.put("security.protocol", "SASL_PLAINTEXT");
        props.put("sasl.mechanism", mechanism);
        props.put("sasl.jaas.config", module + " required username=\"" + user
                + "\" password=\"" + password + "\";");
        props.put("max.block.ms", "5000"); // fail fast instead of waiting a minute
        return props;
    }

    // Starts a one-node KRaft cluster in this JVM with KafkaClusterTestKit, the test
    // cluster EmbeddedKafkaKraftBroker is built on, with SASL and the StandardAuthorizer
    static KafkaClusterTestKit startCluster() throws Exception {
        // logging is off: the clients log every refused request at ERROR, and this
        // program prints the exceptions instead. Logback's Logger is named in full
        // because org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.OFF);
        // the PLAIN users the broker accepts, and the broker's own login (admin)
        String plainUsers = "org.apache.kafka.common.security.plain.PlainLoginModule required"
                + " username=\"admin\" password=\"admin-secret\" user_admin=\"admin-secret\""
                + " user_alice=\"alice-secret\" user_bob=\"bob-secret\";";
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            KafkaClusterTestKit cluster = new KafkaClusterTestKit.Builder(
                    new TestKitNodes.Builder()
                            .setCombined(true)
                            .setNumControllerNodes(1)
                            .setNumBrokerNodes(1)
                            .setBrokerSecurityProtocol(SecurityProtocol.SASL_PLAINTEXT)
                            .setControllerSecurityProtocol(SecurityProtocol.SASL_PLAINTEXT)
                            .build())
                    .setConfigProp("authorizer.class.name",
                            "org.apache.kafka.metadata.authorizer.StandardAuthorizer")
                    .setConfigProp("super.users", "User:admin")
                    // one broker cannot hold the default 3 copies of the internal topics
                    .setConfigProp("offsets.topic.replication.factor", "1")
                    .setConfigProp("transaction.state.log.replication.factor", "1")
                    .setConfigProp("transaction.state.log.min.isr", "1")
                    .setConfigProp("allow.everyone.if.no.acl.found", "false")
                    .setConfigProp("listener.name.external.sasl.enabled.mechanisms",
                            "PLAIN,SCRAM-SHA-512")
                    .setConfigProp("listener.name.external.plain.sasl.jaas.config", plainUsers)
                    .setConfigProp("listener.name.external.scram-sha-512.sasl.jaas.config",
                            "org.apache.kafka.common.security.scram.ScramLoginModule required;")
                    .setConfigProp("listener.name.controller.plain.sasl.jaas.config", plainUsers)
                    .build();
            cluster.format();
            cluster.startup();
            cluster.waitForReadyBrokers();
            return cluster;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
ACL User:alice ALLOW WRITE on TOPIC orders
ACL User:bob ALLOW READ on GROUP billing
ACL User:bob ALLOW READ on TOPIC orders
alice sends to orders: written at offset 0
bob sends to orders: ClusterAuthorizationException: Cluster authorization failed.
bob reads orders as group billing: read "order from alice"
bob reads orders as group audit: GroupAuthorizationException: Not authorized to access group: audit
bob with a wrong password: SaslAuthenticationException: Authentication failed: Invalid username or password
alice lists topics: [orders]
  • alice's record was written at offset 0: she authenticated and holds WRITE on the topic.
  • bob's send failed with ClusterAuthorizationException, not a topic error. Producers are idempotent by default, and starting an idempotent producer needs IDEMPOTENT_WRITE on the cluster, which a principal has implicitly only if it may write to some topic. bob may write nowhere, so the first request already failed.
  • bob read alice's record with the group billing. A consumer in a group needs two ACLs: READ on the topic and READ on the group.
  • With the group audit, the same consumer got GroupAuthorizationException. This is the most common surprise when a team adds a new consumer: the topic ACL alone is not enough.
  • A wrong password failed with SaslAuthenticationException before any request was made.
  • alice's topic list contained orders, because WRITE implies DESCRIBE. Topics a principal cannot describe are left out of its metadata, as if they did not exist.

With PLAIN, the users and passwords sit in clear text in the broker's JAAS configuration, here listener.name.external.plain.sasl.jaas.config, and adding a user means changing every broker's configuration. PLAIN sends the password as is, so it is safe only inside TLS. Use it for a few service accounts, with a custom sasl.server.callback.handler.class that checks an external store, or move to SCRAM.

SCRAM users managed at runtime

SCRAM fixes both problems of PLAIN: the cluster stores only a salted hash of each password, and the password never crosses the network. Credentials live in the KRaft metadata log, so the Admin API can add, rotate and remove users without restarting anything:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.ScramCredentialInfo;
import org.apache.kafka.clients.admin.ScramMechanism;
import org.apache.kafka.clients.admin.UserScramCredentialDeletion;
import org.apache.kafka.clients.admin.UserScramCredentialUpsertion;
import org.apache.kafka.common.security.auth.SecurityProtocol;
import org.apache.kafka.common.test.KafkaClusterTestKit;
import org.apache.kafka.common.test.TestKitNodes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ScramUsers {

    public static void main(String[] args) throws Exception {
        KafkaClusterTestKit cluster = startCluster();
        String bootstrap = cluster.bootstrapServers();
        try (Admin admin = Admin.create(client(bootstrap, "PLAIN", "admin", "admin-secret"))) {
            System.out.println("carol before: " + login(bootstrap, "carol", "carol-secret"));

            // the broker stores a salted hash, never the password itself
            admin.alterUserScramCredentials(List.of(new UserScramCredentialUpsertion("carol",
                    new ScramCredentialInfo(ScramMechanism.SCRAM_SHA_512, 8192),
                    "carol-secret"))).all().get();
            Thread.sleep(500); // the credential reaches the broker through the metadata log
            admin.describeUserScramCredentials().all().get().forEach((user, d) ->
                    System.out.println("stored for " + user + ": " + d.credentialInfos()));
            System.out.println("carol after:  " + login(bootstrap, "carol", "carol-secret"));
            System.out.println("carol, wrong: " + login(bootstrap, "carol", "secret"));

            // a new password replaces the old one at once
            admin.alterUserScramCredentials(List.of(new UserScramCredentialUpsertion("carol",
                    new ScramCredentialInfo(ScramMechanism.SCRAM_SHA_512, 8192),
                    "carol-rotated"))).all().get();
            Thread.sleep(500);
            System.out.println("old password: " + login(bootstrap, "carol", "carol-secret"));
            System.out.println("new password: " + login(bootstrap, "carol", "carol-rotated"));

            admin.alterUserScramCredentials(List.of(new UserScramCredentialDeletion("carol",
                    ScramMechanism.SCRAM_SHA_512))).all().get();
            Thread.sleep(500);
            System.out.println("after delete: " + login(bootstrap, "carol", "carol-rotated"));
        } finally {
            cluster.close();
        }
    }

    // connects with SCRAM-SHA-512 and asks for the cluster id, which needs no ACL
    static String login(String bootstrap, String user, String password) {
        Map<String, Object> props = client(bootstrap, "SCRAM-SHA-512", user, password);
        props.put("request.timeout.ms", "5000");
        props.put("default.api.timeout.ms", "5000");
        try (Admin admin = Admin.create(props)) {
            admin.describeCluster().clusterId().get();
            return "authenticated";
        } catch (ExecutionException e) {
            return e.getCause().getClass().getSimpleName() + ": " + e.getCause().getMessage();
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }

    // Client settings for SASL over plaintext; production uses SASL_SSL
    static Map<String, Object> client(String bootstrap, String mechanism, String user,
            String password) {
        String module = mechanism.equals("PLAIN")
                ? "org.apache.kafka.common.security.plain.PlainLoginModule"
                : "org.apache.kafka.common.security.scram.ScramLoginModule";
        Map<String, Object> props = new HashMap<>();
        props.put("bootstrap.servers", bootstrap);
        props.put("security.protocol", "SASL_PLAINTEXT");
        props.put("sasl.mechanism", mechanism);
        props.put("sasl.jaas.config", module + " required username=\"" + user
                + "\" password=\"" + password + "\";");
        props.put("max.block.ms", "5000"); // fail fast instead of waiting a minute
        return props;
    }

    // Starts a one-node KRaft cluster in this JVM with KafkaClusterTestKit, the test
    // cluster EmbeddedKafkaKraftBroker is built on, with SASL and the StandardAuthorizer
    static KafkaClusterTestKit startCluster() throws Exception {
        // logging is off: the clients log every refused request at ERROR, and this
        // program prints the exceptions instead. Logback's Logger is named in full
        // because org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.OFF);
        // the PLAIN users the broker accepts, and the broker's own login (admin)
        String plainUsers = "org.apache.kafka.common.security.plain.PlainLoginModule required"
                + " username=\"admin\" password=\"admin-secret\" user_admin=\"admin-secret\""
                + " user_alice=\"alice-secret\" user_bob=\"bob-secret\";";
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            KafkaClusterTestKit cluster = new KafkaClusterTestKit.Builder(
                    new TestKitNodes.Builder()
                            .setCombined(true)
                            .setNumControllerNodes(1)
                            .setNumBrokerNodes(1)
                            .setBrokerSecurityProtocol(SecurityProtocol.SASL_PLAINTEXT)
                            .setControllerSecurityProtocol(SecurityProtocol.SASL_PLAINTEXT)
                            .build())
                    .setConfigProp("authorizer.class.name",
                            "org.apache.kafka.metadata.authorizer.StandardAuthorizer")
                    .setConfigProp("super.users", "User:admin")
                    // one broker cannot hold the default 3 copies of the internal topics
                    .setConfigProp("offsets.topic.replication.factor", "1")
                    .setConfigProp("transaction.state.log.replication.factor", "1")
                    .setConfigProp("transaction.state.log.min.isr", "1")
                    .setConfigProp("allow.everyone.if.no.acl.found", "false")
                    .setConfigProp("listener.name.external.sasl.enabled.mechanisms",
                            "PLAIN,SCRAM-SHA-512")
                    .setConfigProp("listener.name.external.plain.sasl.jaas.config", plainUsers)
                    .setConfigProp("listener.name.external.scram-sha-512.sasl.jaas.config",
                            "org.apache.kafka.common.security.scram.ScramLoginModule required;")
                    .setConfigProp("listener.name.controller.plain.sasl.jaas.config", plainUsers)
                    .build();
            cluster.format();
            cluster.startup();
            cluster.waitForReadyBrokers();
            return cluster;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
carol before: SaslAuthenticationException: Authentication failed during authentication due to invalid credentials with SASL mechanism SCRAM-SHA-512
stored for carol: [ScramCredentialInfo{mechanism=SCRAM_SHA_512, iterations=8192}]
carol after:  authenticated
carol, wrong: SaslAuthenticationException: Authentication failed during authentication due to invalid credentials with SASL mechanism SCRAM-SHA-512
old password: SaslAuthenticationException: Authentication failed during authentication due to invalid credentials with SASL mechanism SCRAM-SHA-512
new password: authenticated
after delete: SaslAuthenticationException: Authentication failed during authentication due to invalid credentials with SASL mechanism SCRAM-SHA-512
  • Before carol had a credential, her SCRAM login failed. The message does not say whether the user is unknown or the password is wrong, so it gives an attacker nothing to probe.
  • alterUserScramCredentials stored a SCRAM-SHA-512 credential with 8192 iterations. describeUserScramCredentials returns only the mechanism and the iteration count; the hash and salt never leave the cluster.
  • carol then logged in, and a wrong password failed with the same message as before.
  • Setting a new password replaced the old one at once: the old password failed, the new one worked. Clients that are already connected stay connected; the check happens at login.
  • After the credential was deleted, carol could no longer log in.

A new KRaft cluster cannot accept SCRAM logins until a credential exists, and the brokers may need one for their own connections. For that, kafka-storage.sh format --add-scram writes the first credentials into the metadata when the cluster is formatted. The broker listener needs sasl.enabled.mechanisms to include SCRAM-SHA-512 and a ScramLoginModule entry, as in startCluster. Each login costs the broker the configured number of hash iterations, so very high counts slow down reconnect storms.

TLS and client certificates

TLS encrypts the connection and, with ssl.client.auth=required, also authenticates the client by its certificate. This program creates self-signed certificates for the broker, alice and mallory with keytool, adds a TLS listener that requires client certificates, and maps each certificate's subject to a user name:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.KafkaException;
import org.apache.kafka.common.acl.AccessControlEntry;
import org.apache.kafka.common.acl.AclBinding;
import org.apache.kafka.common.acl.AclOperation;
import org.apache.kafka.common.acl.AclPermissionType;
import org.apache.kafka.common.network.ListenerName;
import org.apache.kafka.common.resource.PatternType;
import org.apache.kafka.common.resource.ResourcePattern;
import org.apache.kafka.common.resource.ResourceType;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.common.test.KafkaClusterTestKit;
import org.apache.kafka.common.test.TestKitNodes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MutualTls {

    static final String PASS = "changeit";

    public static void main(String[] args) throws Exception {
        Path dir = Files.createTempDirectory("tls");
        // one self-signed certificate per party; each side trusts the others' certificates
        keytool(dir, "-genkeypair", "-alias", "broker", "-keyalg", "RSA", "-dname",
                "CN=localhost", "-ext", "SAN=dns:localhost,ip:127.0.0.1", "-validity", "2",
                "-keystore", "broker.p12", "-storepass", PASS);
        for (String user : List.of("alice", "mallory")) {
            keytool(dir, "-genkeypair", "-alias", user, "-keyalg", "RSA", "-dname",
                    "CN=" + user + ",O=Shop", "-validity", "2", "-keystore", user + ".p12",
                    "-storepass", PASS);
            keytool(dir, "-exportcert", "-alias", user, "-keystore", user + ".p12",
                    "-storepass", PASS, "-file", user + ".crt");
            keytool(dir, "-importcert", "-noprompt", "-alias", user, "-file", user + ".crt",
                    "-keystore", "broker-trust.p12", "-storepass", PASS);
        }
        keytool(dir, "-exportcert", "-alias", "broker", "-keystore", "broker.p12",
                "-storepass", PASS, "-file", "broker.crt");
        keytool(dir, "-importcert", "-noprompt", "-alias", "broker", "-file", "broker.crt",
                "-keystore", "client-trust.p12", "-storepass", PASS);

        KafkaClusterTestKit cluster = startCluster(dir);
        int tlsPort = cluster.brokers().get(0).boundPort(new ListenerName("TLS"));
        String tls = "localhost:" + tlsPort;
        try (Admin admin = Admin.create(Map.<String, Object>of(
                "bootstrap.servers", cluster.bootstrapServers()))) {
            admin.createTopics(List.of(new NewTopic("orders", 1, (short) 1))).all().get();
            admin.createAcls(List.of(new AclBinding(
                    new ResourcePattern(ResourceType.TOPIC, "orders", PatternType.LITERAL),
                    new AccessControlEntry("User:alice", "*", AclOperation.WRITE,
                            AclPermissionType.ALLOW)))).all().get();
        }

        send("no truststore", tls, null, null);
        send("truststore, no certificate", tls, dir.resolve("client-trust.p12"), null);
        send("alice's certificate", tls, dir.resolve("client-trust.p12"),
                dir.resolve("alice.p12"));
        send("mallory's certificate", tls, dir.resolve("client-trust.p12"),
                dir.resolve("mallory.p12"));
        cluster.close();
    }

    static void send(String label, String bootstrap, Path trust, Path key) {
        Map<String, Object> props = new HashMap<>(Map.of(
                "bootstrap.servers", bootstrap, "security.protocol", "SSL",
                "max.block.ms", "5000"));
        if (trust != null) {
            props.put("ssl.truststore.location", trust.toString());
            props.put("ssl.truststore.password", PASS);
        }
        if (key != null) {
            props.put("ssl.keystore.location", key.toString());
            props.put("ssl.keystore.password", PASS);
        }
        try (KafkaProducer<String, String> producer = new KafkaProducer<>(props,
                new StringSerializer(), new StringSerializer())) {
            long offset = producer.send(new ProducerRecord<>("orders", label)).get().offset();
            System.out.println(label + ": written at offset " + offset);
        } catch (ExecutionException | KafkaException e) {
            Throwable cause = e instanceof ExecutionException ? e.getCause() : e;
            System.out.println(label + ": " + cause.getClass().getSimpleName());
            Throwable root = cause;
            while (root.getCause() != null) {
                root = root.getCause();
            }
            if (root != cause) {
                System.out.println("  root cause: " + root.getClass().getSimpleName() + ": "
                        + root.getMessage());
            }
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }

    static void keytool(Path dir, String... args) throws Exception {
        List<String> command = new ArrayList<>();
        command.add(Path.of(System.getProperty("java.home"), "bin", "keytool").toString());
        command.addAll(List.of(args));
        command.addAll(List.of("-storetype", "PKCS12"));
        Process p = new ProcessBuilder(command).directory(dir.toFile())
                .redirectErrorStream(true).start();
        String out = new String(p.getInputStream().readAllBytes());
        if (p.waitFor() != 0) {
            throw new IllegalStateException(out);
        }
    }

    // Starts a one-node KRaft cluster in this JVM with KafkaClusterTestKit and adds a TLS
    // listener that requires client certificates. The plaintext listener the test kit
    // always creates stands in for a private admin network here.
    static KafkaClusterTestKit startCluster(Path dir) throws Exception {
        // logging is off: refused connections are logged at ERROR, and the program
        // prints them instead. Logback's Logger is named in full: org.slf4j.Logger,
        // imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.OFF);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            String tls = "listener.name.tls.";
            KafkaClusterTestKit cluster = new KafkaClusterTestKit.Builder(
                    new TestKitNodes.Builder().setCombined(true).setNumControllerNodes(1)
                            .setNumBrokerNodes(1).build())
                    .setConfigProp("listeners",
                            "EXTERNAL://localhost:0,CONTROLLER://localhost:0,TLS://localhost:0")
                    .setConfigProp("listener.security.protocol.map",
                            "EXTERNAL:PLAINTEXT,CONTROLLER:PLAINTEXT,TLS:SSL")
                    .setConfigProp(tls + "ssl.keystore.location",
                            dir.resolve("broker.p12").toString())
                    .setConfigProp(tls + "ssl.keystore.password", PASS)
                    .setConfigProp(tls + "ssl.truststore.location",
                            dir.resolve("broker-trust.p12").toString())
                    .setConfigProp(tls + "ssl.truststore.password", PASS)
                    .setConfigProp(tls + "ssl.client.auth", "required")
                    // turns the certificate subject "CN=alice,O=Shop" into the user "alice"
                    .setConfigProp("ssl.principal.mapping.rules",
                            "RULE:^CN=([^,]+),.*$/$1/,DEFAULT")
                    .setConfigProp("authorizer.class.name",
                            "org.apache.kafka.metadata.authorizer.StandardAuthorizer")
                    .setConfigProp("super.users", "User:ANONYMOUS")
                    .setConfigProp("offsets.topic.replication.factor", "1")
                    .build();
            cluster.format();
            cluster.startup();
            cluster.waitForReadyBrokers();
            return cluster;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
no truststore: SslAuthenticationException
  root cause: SunCertPathBuilderException: unable to find valid certification path to requested target
truststore, no certificate: SslAuthenticationException
  root cause: SSLHandshakeException: (certificate_required) Received fatal alert: certificate_required
alice's certificate: written at offset 0
mallory's certificate: TopicAuthorizationException
  • Without a truststore, the client used the JDK's default certificate authorities. None of them signed the broker's certificate, so the handshake failed with "unable to find valid certification path".
  • With a truststore but no certificate of its own, the client trusted the broker, but the broker ended the handshake with certificate_required.
  • With alice's certificate, the write succeeded. The rule RULE:^CN=([^,]+),.*$/$1/ in ssl.principal.mapping.rules turned the subject CN=alice,O=Shop into User:alice, which matched the ACL. Without the rule, the principal would be the whole subject, User:CN=alice,O=Shop.
  • mallory's certificate was trusted, so she connected, but she has no ACL and got TopicAuthorizationException. Authentication and authorization are separate checks.

Clients check the broker's host name against the certificate by default (ssl.endpoint.identification.algorithm=https), which is why the broker certificate lists localhost and 127.0.0.1 as subject alternative names. Kafka 4.2 enables TLS 1.2 and 1.3 and prefers 1.3. In production, certificates come from a certificate authority, each truststore holds the CA certificate instead of every peer's certificate, and keystores are reloaded at runtime by changing the listener's ssl.keystore.location with kafka-configs.sh. This program uses the test kit's plaintext listener for the admin work, with User:ANONYMOUS as super user; that shortcut is only for the demonstration.

Prefixed ACLs, DENY and wildcards

Writing one ACL per topic does not scale to hundreds of topics. Kafka ACLs can match a name prefix or every name, and a DENY entry can carve out an exception. This program gives alice write access to all team-a. topics except the payroll topic:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.acl.AccessControlEntry;
import org.apache.kafka.common.acl.AccessControlEntryFilter;
import org.apache.kafka.common.acl.AclBinding;
import org.apache.kafka.common.acl.AclBindingFilter;
import org.apache.kafka.common.acl.AclOperation;
import org.apache.kafka.common.acl.AclPermissionType;
import org.apache.kafka.common.resource.PatternType;
import org.apache.kafka.common.resource.ResourcePattern;
import org.apache.kafka.common.resource.ResourcePatternFilter;
import org.apache.kafka.common.resource.ResourceType;
import org.apache.kafka.common.security.auth.SecurityProtocol;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.common.test.KafkaClusterTestKit;
import org.apache.kafka.common.test.TestKitNodes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AclPatterns {

    static final List<String> TOPICS = List.of("team-a.orders", "team-a.payroll", "team-b.orders");

    public static void main(String[] args) throws Exception {
        KafkaClusterTestKit cluster = startCluster();
        String bootstrap = cluster.bootstrapServers();
        try (Admin admin = Admin.create(client(bootstrap, "PLAIN", "admin", "admin-secret"))) {
            admin.createTopics(TOPICS.stream().map(t -> new NewTopic(t, 1, (short) 1))
                    .toList()).all().get();
            AclBinding denyPayroll = acl(AclPermissionType.DENY, "User:alice",
                    "team-a.payroll", PatternType.LITERAL, AclOperation.WRITE);
            admin.createAcls(List.of(
                    acl(AclPermissionType.ALLOW, "User:alice", "team-a.", PatternType.PREFIXED,
                            AclOperation.WRITE),
                    denyPayroll)).all().get();
            Thread.sleep(500); // ACLs reach the broker through the metadata log
            System.out.println("ALLOW WRITE on prefix team-a., DENY WRITE on team-a.payroll:");
            sendAll(bootstrap);
            System.out.println("alice sees topics " + topicsSeenByAlice(bootstrap));

            admin.createAcls(List.of(acl(AclPermissionType.ALLOW, "User:*", "*",
                    PatternType.LITERAL, AclOperation.DESCRIBE))).all().get();
            Thread.sleep(500);
            System.out.println("with DESCRIBE on * for User:*, alice sees topics "
                    + topicsSeenByAlice(bootstrap));

            AclBindingFilter alicesAcls = new AclBindingFilter(ResourcePatternFilter.ANY,
                    new AccessControlEntryFilter("User:alice", null, AclOperation.ANY,
                            AclPermissionType.ANY));
            admin.describeAcls(alicesAcls).values().get().stream()
                    .map(b -> b.entry().permissionType() + " " + b.entry().operation() + " "
                            + b.pattern().patternType() + " " + b.pattern().name())
                    .sorted()
                    .forEach(a -> System.out.println("  alice: " + a));

            admin.deleteAcls(List.of(denyPayroll.toFilter())).all().get();
            Thread.sleep(500);
            System.out.println("after deleting the DENY:");
            sendAll(bootstrap);
        } finally {
            cluster.close();
        }
    }

    static AclBinding acl(AclPermissionType type, String principal, String name,
            PatternType pattern, AclOperation operation) {
        return new AclBinding(new ResourcePattern(ResourceType.TOPIC, name, pattern),
                new AccessControlEntry(principal, "*", operation, type));
    }

    static void sendAll(String bootstrap) throws Exception {
        try (KafkaProducer<String, String> producer = new KafkaProducer<>(
                client(bootstrap, "PLAIN", "alice", "alice-secret"),
                new StringSerializer(), new StringSerializer())) {
            for (String topic : TOPICS) {
                try {
                    producer.send(new ProducerRecord<>(topic, "hello")).get();
                    System.out.println("  alice writes " + topic + ": ok");
                } catch (ExecutionException e) {
                    System.out.println("  alice writes " + topic + ": "
                            + e.getCause().getClass().getSimpleName());
                }
            }
        }
    }

    static TreeSet<String> topicsSeenByAlice(String bootstrap) throws Exception {
        try (Admin alice = Admin.create(client(bootstrap, "PLAIN", "alice", "alice-secret"))) {
            return new TreeSet<>(alice.listTopics().names().get());
        }
    }

    // Client settings for SASL over plaintext; production uses SASL_SSL
    static Map<String, Object> client(String bootstrap, String mechanism, String user,
            String password) {
        String module = mechanism.equals("PLAIN")
                ? "org.apache.kafka.common.security.plain.PlainLoginModule"
                : "org.apache.kafka.common.security.scram.ScramLoginModule";
        Map<String, Object> props = new HashMap<>();
        props.put("bootstrap.servers", bootstrap);
        props.put("security.protocol", "SASL_PLAINTEXT");
        props.put("sasl.mechanism", mechanism);
        props.put("sasl.jaas.config", module + " required username=\"" + user
                + "\" password=\"" + password + "\";");
        props.put("max.block.ms", "5000"); // fail fast instead of waiting a minute
        return props;
    }

    // Starts a one-node KRaft cluster in this JVM with KafkaClusterTestKit, the test
    // cluster EmbeddedKafkaKraftBroker is built on, with SASL and the StandardAuthorizer
    static KafkaClusterTestKit startCluster() throws Exception {
        // logging is off: the clients log every refused request at ERROR, and this
        // program prints the exceptions instead. Logback's Logger is named in full
        // because org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.OFF);
        // the PLAIN users the broker accepts, and the broker's own login (admin)
        String plainUsers = "org.apache.kafka.common.security.plain.PlainLoginModule required"
                + " username=\"admin\" password=\"admin-secret\" user_admin=\"admin-secret\""
                + " user_alice=\"alice-secret\" user_bob=\"bob-secret\";";
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            KafkaClusterTestKit cluster = new KafkaClusterTestKit.Builder(
                    new TestKitNodes.Builder()
                            .setCombined(true)
                            .setNumControllerNodes(1)
                            .setNumBrokerNodes(1)
                            .setBrokerSecurityProtocol(SecurityProtocol.SASL_PLAINTEXT)
                            .setControllerSecurityProtocol(SecurityProtocol.SASL_PLAINTEXT)
                            .build())
                    .setConfigProp("authorizer.class.name",
                            "org.apache.kafka.metadata.authorizer.StandardAuthorizer")
                    .setConfigProp("super.users", "User:admin")
                    // one broker cannot hold the default 3 copies of the internal topics
                    .setConfigProp("offsets.topic.replication.factor", "1")
                    .setConfigProp("transaction.state.log.replication.factor", "1")
                    .setConfigProp("transaction.state.log.min.isr", "1")
                    .setConfigProp("allow.everyone.if.no.acl.found", "false")
                    .setConfigProp("listener.name.external.sasl.enabled.mechanisms",
                            "PLAIN,SCRAM-SHA-512")
                    .setConfigProp("listener.name.external.plain.sasl.jaas.config", plainUsers)
                    .setConfigProp("listener.name.external.scram-sha-512.sasl.jaas.config",
                            "org.apache.kafka.common.security.scram.ScramLoginModule required;")
                    .setConfigProp("listener.name.controller.plain.sasl.jaas.config", plainUsers)
                    .build();
            cluster.format();
            cluster.startup();
            cluster.waitForReadyBrokers();
            return cluster;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
ALLOW WRITE on prefix team-a., DENY WRITE on team-a.payroll:
  alice writes team-a.orders: ok
  alice writes team-a.payroll: TopicAuthorizationException
  alice writes team-b.orders: TopicAuthorizationException
alice sees topics [team-a.orders, team-a.payroll]
with DESCRIBE on * for User:*, alice sees topics [team-a.orders, team-a.payroll, team-b.orders]
  alice: ALLOW WRITE PREFIXED team-a.
  alice: DENY WRITE LITERAL team-a.payroll
after deleting the DENY:
  alice writes team-a.orders: ok
  alice writes team-a.payroll: ok
  alice writes team-b.orders: TopicAuthorizationException
  • The PREFIXED ACL on team-a. let alice write to team-a.orders. Topics that team-a creates later are covered automatically.
  • The DENY on team-a.payroll won over the prefixed ALLOW. Kafka checks DENY entries first, and any matching DENY refuses the request.
  • team-b.orders matched nothing, so the request was refused.
  • alice could still see team-a.payroll in her topic list: the DENY covers WRITE only, and the prefixed WRITE grant implies DESCRIBE.
  • After an ALLOW of DESCRIBE on * for User:*, alice saw all three topics. The wildcards match every topic and every principal.
  • After the DENY was deleted, the write to team-a.payroll succeeded.

Every request type maps to an operation on a resource type: TOPIC, GROUP, CLUSTER, TRANSACTIONAL_ID and DELEGATION_TOKEN. The common sets are short:

ACLs that common clients need
ClientACLs
ProducerWRITE on the topic (implies DESCRIBE and idempotent writes)
Transactional producerAlso WRITE and DESCRIBE on its TRANSACTIONAL_ID
Consumer in a groupREAD on the topic and READ on the group
Kafka Streams applicationThe above, plus CREATE and DELETE on topics prefixed with its application.id
Operator toolsDESCRIBE or ALTER on CLUSTER, or a super user

From the command line, the same ACLs are managed with kafka-acls.sh --bootstrap-server ... --command-config admin.properties --add --allow-principal User:alice --operation Write --topic team-a. --resource-pattern-type prefixed.

A secured client configuration

In production, the pieces combine into a SASL_SSL listener. The client side below follows the Kafka documentation; it was not run here, since it needs a certificate authority:

Properties
# client.properties: SCRAM login inside TLS
bootstrap.servers=kafka-1:9093,kafka-2:9093,kafka-3:9093
security.protocol=SASL_SSL
sasl.mechanism=SCRAM-SHA-512
sasl.jaas.config=org.apache.kafka.common.security.scram.ScramLoginModule required \
    username="orders-service" password="${file:/etc/kafka/secrets.properties:password}";
ssl.truststore.location=/etc/kafka/ca-truststore.p12
ssl.truststore.password=${file:/etc/kafka/secrets.properties:truststore}
config.providers=file
config.providers.file.class=org.apache.kafka.common.config.provider.FileConfigProvider
  • Passwords out of the file: the FileConfigProvider replaces each ${file:...} reference with a value from another file, which can have stricter permissions or come from a secrets manager.
  • The broker side: the listener needs listeners=SASL_SSL://:9093, a keystore, sasl.enabled.mechanisms, and authorizer.class.name=org.apache.kafka.metadata.authorizer.StandardAuthorizer on brokers and controllers.
  • Inter-broker and controller traffic: inter.broker.listener.name and controller.listener.names should point at secured listeners too, with the brokers' own principals in super.users.
  • Spring Boot: the same keys go under spring.kafka.security.protocol, spring.kafka.properties.sasl.mechanism and spring.kafka.properties.sasl.jaas.config, and spring.kafka.ssl.*.

Choosing a security setup

Situations and the setup that fits
SituationSetup
Services with users and passwordsSASL_SSL with SCRAM-SHA-512, users managed by the Admin API
A company PKI already issues service certificatesSSL with ssl.client.auth=required and principal mapping rules
Central identity provider with short-lived tokensSASL_SSL with OAUTHBEARER and OIDC
Kerberos and Active Directory everywhereSASL_SSL with GSSAPI
Many topics per teamPREFIXED ACLs on a naming convention such as team.domain.
One sensitive topic inside a team's prefixA DENY ACL on that topic
Development on a laptopPLAINTEXT, never reachable from other machines

Securing a cluster also changes how it is operated: every tool on Kafka cluster administration then needs --command-config with client settings like those above. Authorization failures show up as error metrics and in the broker's authorizer log, which Kafka monitoring covers. The producer and consumer settings themselves are explained on the Kafka producer and the Kafka consumer pages.