Authentication with SASL in Apache Kafka
How Kafka brokers find out who is knocking on the door, the four main SASL mechanisms compared, and how to set up, rotate, monitor and troubleshoot authentication without breaking your streaming platform.
Imagine an office building with a busy front desk. Anyone can walk in, ask for a file from the archive room, and walk out again, because nobody at the desk ever asks who they are. That works for a tiny club, but the moment the building holds payroll records and customer files, the desk needs to check identity before doing anything else. Only after the visitor proves who they are can the desk decide which rooms they may enter. In Kafka, the front desk is the broker, the identity check is authentication, and SASL is one of the most common ways to carry out that check.
This tutorial starts with the basic problem and builds up slowly. We look at what SASL is, how a connection is set up and checked, and the four main mechanisms Kafka supports. We then cover configuration ideas, credential lifecycle, roll-out planning, monitoring and troubleshooting. Every new term is explained when it first appears, with an everyday comparison.
1The Problem: An Open Kafka Cluster
Before learning any mechanism, it helps to see what an unprotected Kafka cluster allows.
A quick Kafka refresher
Apache Kafka stores streams of events in topics. Producers write events, consumers read them, and brokers, the servers of the Kafka cluster, store and serve them. Around the brokers live many other programs: stream processors, connectors that move data in and out of databases, monitoring tools and administration tools. All of them connect to the brokers over the network.
What happens with no security
A freshly installed Kafka cluster with default settings accepts any connection from anyone who can reach it over the network. There is no question about who the client is. A curious or careless person can read any topic, write fake events to any topic, delete topics, or change settings. A misconfigured test program can accidentally flood production topics. There is also no way to tell later who did what, because everyone looks the same.
Data theft
Anyone on the network can read sensitive events such as orders, payments or personal details.
Data tampering
Fake or harmful events can be written into topics that other systems trust.
Destructive actions
Topics can be deleted and settings changed by anyone, deliberately or by mistake.
No accountability
Without identities, logs cannot show which application or person performed an action.
An unprotected cluster is like a library with no membership cards and no staff at the entrance. Anyone can borrow, return, mark or remove any book, and afterwards nobody can say who did it.
2Three Separate Ideas: Authentication, Authorization and Encryption
People often blur these words together. Kafka treats them as three different layers, each solving a different problem.
Authentication
Proving who you are. Answers the question “who is this client?”
Authorization
Deciding what an identified client may do. Answers “is this client allowed to read or write this topic?”
Encryption
Hiding data while it travels over the network. Answers “can anyone listening in read this?”
flowchart LR
C["Client connects"] --> E["Encryption: is the channel private?"]
E --> A["Authentication: who are you?"]
A --> Z["Authorization: what may you do?"]
Z --> D["Request allowed or denied"]
At an airport, the passport check proves who you are, which is authentication. The boarding pass decides which flight you may board, which is authorization. The curtained booth where you talk to the officer keeps others from overhearing, which is encryption. A passport does not let you board every plane, and a boarding pass is useless if nobody checked the passport.
Where SASL fits
SASL belongs to the first of the three layers. It is a way of proving identity. It does not decide permissions, which are handled by access control lists, and by itself it does not encrypt the traffic, which is handled by TLS. A secure setup normally uses all three together, and this tutorial focuses on the first.
Believing that turning on SASL makes the cluster fully secure. It proves identity, but without permission rules every authenticated user may still be allowed to do everything, and without encryption some mechanisms expose secrets on the wire.
3What Is SASL?
SASL is not a single login method. It is a framework that lets many login methods plug into a protocol.
The name
SASL stands for Simple Authentication and Security Layer. It is an internet standard that separates the question “how does this application protocol carry authentication messages?” from the question “which method is used to prove identity?” A protocol that supports SASL, such as email or directory services, can offer many methods without redesigning itself each time.
How Kafka uses it
Kafka adopted SASL so that brokers can support several authentication methods through one common pattern. Each method is called a mechanism. Kafka defines the steps by which a client and a broker agree on a mechanism and then exchange a series of messages that belong to that mechanism. Adding a new mechanism does not change how the rest of Kafka works.
SASL is like the reception desk procedure in a large company: ask the visitor to state which type of ID they hold, then follow the matching checking procedure for a passport, a staff card or a driving licence. The desk procedure stays the same. Only the ID-specific steps differ.
Mechanisms Kafka ships with
PLAIN
A simple username and password. Easy to set up, and safe only when the connection is encrypted.
SCRAM
A password method where the password itself is never sent. Available with two strengths, SHA-256 and SHA-512.
GSSAPI (Kerberos)
Ticket-based single sign-on used in many large organisations that already run Kerberos.
OAUTHBEARER
Token-based authentication, where a client presents a token issued by a trusted identity provider.
4Listeners and Security Protocols
Before authentication can happen, Kafka must know which doors the broker has and how each door is protected.
Listeners
A listener is a network address and port on which a broker accepts connections. A broker can have several listeners at once, for example one for applications inside the company network and another for outside partners. Each listener has a name and is given its own security protocol, so different doors can have different levels of protection.
The four security protocols
| Protocol | Encrypted Channel | Identity Check | Typical Use |
|---|---|---|---|
| PLAINTEXT | No | No | Isolated test environments only |
| SSL (TLS) | Yes | Optional, through client certificates | Encryption alone, or certificate-based identity |
| SASL_PLAINTEXT | No | Yes, through SASL | Trusted private networks, and never with PLAIN over untrusted networks |
| SASL_SSL | Yes | Yes, through SASL | Most production deployments |
Think of four kinds of doors: an open doorway, a soundproof door without a guard, a guarded door where people talk in a public hallway, and a guarded, soundproof door. The last is the one you want for anything valuable.
Why the last one matters
SASL_PLAINTEXT proves identity but sends everything else, including your event data, unencrypted. Some mechanisms also expose the secret itself in that case. SASL_SSL wraps the entire conversation in TLS encryption first, then runs the SASL identity check inside it. Almost every production setup uses SASL_SSL.
Using SASL_PLAINTEXT with the PLAIN mechanism across a network. The username and password travel in readable form, so anyone who can observe the traffic can steal them.
5How a SASL Connection Is Established
Every SASL login in Kafka follows the same short conversation before any events can flow.
sequenceDiagram
participant C as Client
participant B as Broker
C->>B: Open connection to the listener
C->>B: Ask which API versions are supported
B-->>C: Supported versions
C->>B: Handshake: I want to use mechanism X
B-->>C: Mechanism X is enabled, continue
C->>B: Mechanism-specific message 1
B-->>C: Mechanism-specific reply
C->>B: Further messages until finished
B-->>C: Authentication successful
Note over C,B: Normal Kafka requests can now flow
Connect to the right listener
The client opens a network connection to a listener that is configured for a SASL protocol. If the listener expects plain traffic, the conversation will fail.
Encrypt the channel when TLS is used
For SASL_SSL, a TLS handshake happens first, including the client checking the broker’s certificate. Only then does SASL begin.
Negotiate the mechanism
The client states which mechanism it wants. The broker replies with its enabled list. If the client’s choice is not on the list, the broker refuses and shows the list.
Exchange mechanism messages
The two sides swap a few messages defined by the mechanism. A password mechanism may need one or two messages. A ticket-based mechanism may need more.
Success or failure
If the proof checks out, the broker records the client’s identity for this connection. If not, the broker closes the connection and the client reports an authentication error.
Normal requests begin
From now on every request on that connection is treated as coming from the authenticated identity.
Arriving at an office reception, you say which kind of ID you are carrying, the receptionist confirms they accept that kind, you go through the checking steps for that ID, and only after a green light do you get a visitor badge and access to the building.
Authentication happens once per connection, not once per request. This keeps normal traffic fast, but it also means an identity stays valid for as long as the connection lives unless the broker forces a fresh check, a point covered in the chapter on credential lifecycle.
6From Login to Identity: The Principal
Authentication produces one valuable result: a name the broker can use for permissions and for logs.
What a principal is
After successful authentication, the broker attaches a principal to the connection. A principal is simply the identity name of the client, such as a user name or a service name. Every later request on that connection is tagged with the principal. This is how the authorization layer knows whose permissions to check, and how logs can record who did what.
Where the name comes from
The principal depends on the mechanism. For password mechanisms it is the user name. For Kerberos it is derived from the Kerberos principal, often shortened by mapping rules that strip the realm and host parts. For token mechanisms it is taken from a claim inside the token, such as the subject. Administrators should know exactly which name each mechanism yields, because permissions are written against these names.
flowchart LR
A["Successful SASL login"] --> P["Principal, for example User:payments-app"]
P --> ACL["Access control rules match the principal"]
P --> LOG["Logs and metrics record the principal"]
P --> Q["Quotas can be applied per principal"]
The visitor badge given at reception carries a name. The security guards at each door read the badge to decide who may enter, the camera log records the badge holder, and the canteen limits how many meals each badge may claim.
Permissions
Access control rules grant read and write rights to specific principals.
Auditing
Logs show which principal created, read or deleted a topic.
Quotas
Bandwidth and request limits can be assigned per principal to protect other users.
Troubleshooting
Errors can be traced to a specific application by its identity.
Sharing one identity across many applications. Permissions become too broad, logs become meaningless, and rotating a secret forces every application to change at the same moment. Give each application its own identity.
7Mechanism One: SASL/PLAIN
The simplest mechanism sends a username and password, and everything depends on the channel being private.
How it works
The client sends its username and password to the broker in a single message. The broker checks them against its list of known users and replies with success or failure. There are no extra steps. This simplicity makes PLAIN the easiest mechanism to understand and the easiest to test.
Where the passwords live
By default, Kafka’s PLAIN support reads the list of valid users and passwords from the broker’s login configuration, which is a text file or a configuration property. That means adding or changing a user requires editing that configuration, and often restarting or reloading brokers. In real deployments, teams usually replace this default with a custom check that consults a central store, such as a directory service or a secrets database, so passwords are not kept in plain text in files.
sequenceDiagram
participant C as Client
participant T as TLS channel
participant B as Broker
C->>T: Encrypted tunnel established
C->>B: Username and password, inside the tunnel
B->>B: Compare with stored credentials
B-->>C: Success or failure
Advantages
- Very easy to understand and configure
- Supported by practically every Kafka client library
- Works well with an external password store through a custom check
- Good for quick development and small setups
Disadvantages / Trade-offs
- The password itself is sent to the broker, so TLS is essential
- Default storage keeps passwords in configuration files
- Changing users often needs broker configuration changes
- Long-lived shared passwords are hard to rotate safely
PLAIN is like saying your secret password aloud to the guard. It is fine in a soundproof booth, and dangerous in a crowded corridor.
Use PLAIN only with TLS. If you like its simplicity but need central control over credentials, connect it to an external identity store rather than keeping passwords in broker files.
8Mechanism Two: SASL/SCRAM
SCRAM lets the client prove it knows the password without ever sending the password.
Challenge and response
SCRAM stands for Salted Challenge Response Authentication Mechanism. Instead of sending the password, the client and broker exchange random values. The broker sends a challenge, and the client answers with a calculation that only someone who knows the password could perform. The broker checks the answer using stored verification data. Kafka also lets the client verify that the broker knows the right data, so both sides prove themselves to each other.
What the broker stores
The broker does not store the password. It stores a salted, transformed version that lets it check answers but does not reveal the original password. A salt is a random value mixed in so that two users with the same password have different stored data, which defeats pre-made lookup tables. Kafka supports two strengths, named after the hashing methods SHA-256 and SHA-512.
sequenceDiagram
participant C as Client
participant B as Broker
C->>B: Hello, my user name and a random value
B-->>C: Challenge: salt, iteration count, my random value
C->>C: Compute proof using the password
C->>B: Proof of knowing the password
B->>B: Verify proof against stored data
B-->>C: Success and broker's own proof
C->>C: Verify broker's proof
Managing SCRAM users
SCRAM credentials are stored inside Kafka’s own cluster metadata and are created and changed with the standard administration tools. Adding, changing or removing a user does not require restarting brokers. This makes day-to-day user management much easier than with file-based PLAIN. Support for managing SCRAM users when the cluster uses Kafka’s own controller quorum instead of an external coordination service arrived in recent versions, so check the version you run.
Advantages
- Password is never sent over the network
- Salted storage protects against stolen data
- Users can be added or changed without restarting brokers
- Mutual proof: client also verifies the broker
- No extra infrastructure beyond Kafka itself
Disadvantages / Trade-offs
- Still needs TLS to protect the data and to stop certain attacks
- Credentials live in Kafka metadata, so access to metadata must be guarded
- No built-in link to company directories or single sign-on
- Passwords still need rotation discipline
SCRAM is like a shared secret handshake that changes each time. The guard shows a random pattern, and the visitor replies with the matching sequence that only a person who knows the secret could produce, without ever speaking the secret aloud.
SCRAM is a popular choice for teams that want password-style authentication with better protection than PLAIN and no external systems to run. Prefer the stronger SHA-512 variant unless a client library limits you.
9Mechanism Three: SASL/GSSAPI with Kerberos
Kerberos gives an organisation one central place for logins, and Kafka can join in as one of the services.
The cast of characters
Kerberos is a ticket-based authentication system used widely in large enterprises. It has a central server called the key distribution center, which knows every user and service in the organisation. Each user or service has a principal name in a realm, which is the administrative domain. Services such as Kafka brokers have keytab files, which hold their long-term secrets so they can run without a human typing a password.
How a login works
A client first proves its identity to the key distribution center and receives a ticket-granting ticket, a kind of master pass. When it wants to talk to Kafka, it shows that master pass to the center and asks for a service ticket for the Kafka broker. It presents this service ticket to the broker. The broker can verify the ticket using its own secret, without calling the center each time. No password crosses the network to Kafka.
sequenceDiagram
participant C as Client
participant K as Key distribution center
participant B as Kafka broker
C->>K: Prove identity, ask for master ticket
K-->>C: Ticket-granting ticket
C->>K: Show master ticket, ask for Kafka service ticket
K-->>C: Service ticket for the Kafka broker
C->>B: Present service ticket
B->>B: Verify ticket with own keytab
B-->>C: Authenticated
Kerberos is like a theme park. You prove who you are at the main gate and get a day pass. At each ride you show the day pass at the ticket booth to get a ride token, then hand the token to the ride operator. The ride never sees your passport and never has to call the main gate.
Details that trip teams up
Names and DNS must match
Service tickets are issued for a specific service name and host name. If clients connect using a name that does not match the broker’s registered principal, authentication fails. Consistent, correct DNS is essential.
Clocks must agree
Tickets carry timestamps and are accepted only within a short time window. If a machine’s clock drifts too far, its tickets are rejected. Reliable time synchronisation is a firm requirement.
Keytabs are sensitive files
A keytab file lets its holder act as the service. It must be protected with tight file permissions, and delivered and rotated through a controlled process.
The central authority is a dependency
If the key distribution center is unavailable, new tickets cannot be issued. Existing tickets keep working until they expire, but the risk must be planned for with redundancy.
Name mapping to principals
Kerberos names carry realm and host parts. Rules shorten them into simple principals for permissions, so these rules must be designed and tested carefully.
Advantages
- Single sign-on with existing corporate identities
- No passwords sent to Kafka
- Central control over who exists and who is disabled
- Mature and widely audited technology
Disadvantages / Trade-offs
- Heavy setup and operational complexity
- Sensitive to DNS and clock problems
- Keytab management burden
- Less natural for cloud-native and container environments
10Mechanism Four: SASL/OAUTHBEARER
OAUTHBEARER lets clients authenticate with short-lived tokens from a central identity provider.
The token idea
In token-based authentication, a client first obtains a token from an identity provider, a trusted service that knows who is who. A token is a small signed piece of data that says who the holder is and how long the token is valid. The client presents the token to the Kafka broker. The broker checks the signature and the expiry, and if they are good, accepts the client’s identity from the token.
Why organisations like it
Tokens expire quickly, often within minutes or hours, so a stolen token is only briefly useful. The identity provider is a single place to control who may get tokens, and it often already supports login for humans and services across the whole company. Applications running in containers or cloud platforms can obtain tokens from the platform’s own identity system without any long-lived secret stored in files.
sequenceDiagram
participant C as Client
participant I as Identity provider
participant B as Kafka broker
C->>I: Prove identity, request token
I-->>C: Signed short-lived token
C->>B: Present token
B->>B: Check signature, expiry and claims
B-->>C: Authenticated as the token's subject
Note over C,I: Client refreshes the token before it expires
Built-in and custom support
Kafka defines the OAUTHBEARER mechanism and, for a long time, shipped only a basic unsecured implementation meant for testing. Recent versions include built-in support for standard token flows, where the client fetches tokens from an identity provider and the broker validates them against the provider’s published signing keys. Many organisations also use vendor-supplied or custom handlers. Whichever route you choose, confirm that your version and client libraries support it, and never use the unsecured testing implementation in production.
A token is like a concert wristband that expires at midnight. Once the box office verifies you and gives you the wristband, staff inside only look at the wristband and its colour, not your original ticket. If you lose it, it stops being useful soon.
Advantages
- Short-lived credentials limit the damage of leaks
- Central identity provider for people and services
- No long-lived password stored in application files
- Fits cloud and container platforms well
Disadvantages / Trade-offs
- Needs an identity provider to be available and secure
- Client libraries differ in level of support
- Token refresh and expiry handling must be designed
- More moving parts than password mechanisms
Using the default unsecured token handler that ships for development and testing. It accepts tokens without proper verification and gives a false sense of security.
11Related Options: Certificates, Delegation Tokens and Cloud Mechanisms
SASL is not the only way to identify a Kafka client, and some environments add their own twists.
Mutual TLS with client certificates
Instead of SASL, a client can prove identity using a TLS certificate. The broker is set to request a client certificate, checks that it was signed by a trusted authority, and takes the principal from the certificate’s subject name. This is called mutual TLS because both sides present certificates. It needs a public key infrastructure to issue, distribute and renew certificates, which can be a large task, but it combines encryption and identity in one step.
Delegation tokens
Delegation tokens are a lightweight feature that lets an already authenticated user obtain a temporary token, which other processes can use to authenticate with the same rights. They rely on the SCRAM mechanism. They are useful for distributed processing frameworks that start many worker processes, since the workers do not need access to the original user’s long-term credentials.
Cloud and vendor mechanisms
Managed Kafka services often add their own SASL mechanisms so that clients can authenticate with the cloud platform’s own identity system. One well-known example is a mechanism that lets applications use their cloud identity and access management roles instead of stored passwords. These mechanisms follow the same SASL pattern, but are supported only on the platform that provides them and need matching client libraries.
| Option | Proof of Identity | Main Setup Effort | Good Fit |
|---|---|---|---|
| SASL/PLAIN | Username and password | Low | Development and small setups, with TLS |
| SASL/SCRAM | Password proven without being sent | Low to medium | Self-managed clusters wanting simple, safer passwords |
| SASL/GSSAPI | Kerberos tickets | High | Organisations already using Kerberos |
| SASL/OAUTHBEARER | Signed short-lived token | Medium to high | Central identity provider, cloud-native environments |
| Mutual TLS | Client certificate | Medium to high | Organisations with strong certificate infrastructure |
| Cloud-specific SASL | Platform identity | Low on that platform | Managed services with matching mechanisms |
These are different kinds of ID cards a building may accept: a shared password, a secret handshake, a company badge issued by head office, a short-lived visitor wristband, a passport-style certificate, or a landlord’s key for that specific building. Each has its own issuing process and rules.
12Choosing a Mechanism
The right mechanism depends on what your organisation already has and how much complexity it can carry.
flowchart TD
S["Which mechanism?"] --> Q1{"Already have Kerberos across the company?"}
Q1 -- "Yes" --> G["GSSAPI"]
Q1 -- "No" --> Q2{"Central identity provider issuing tokens?"}
Q2 -- "Yes" --> O["OAUTHBEARER"]
Q2 -- "No" --> Q3{"Strong certificate infrastructure?"}
Q3 -- "Yes" --> M["Consider mutual TLS"]
Q3 -- "No" --> Q4{"Want to avoid sending passwords and extra systems?"}
Q4 -- "Yes" --> SC["SCRAM"]
Q4 -- "No, quick test only" --> PL["PLAIN with TLS"]
Questions to ask before choosing
What identity system exists?
Reusing an existing directory, Kerberos realm or identity provider avoids creating another list of users.
Who are the clients?
Long-running services, short-lived jobs, containers and humans have different needs for credential delivery.
What do client libraries support?
Some languages support only a subset of mechanisms. Check every client type in your estate.
How will credentials rotate?
A mechanism that is easy to start but painful to rotate becomes a long-term burden.
What are the compliance needs?
Some regulations favour central identity, short-lived credentials or detailed audit trails.
What can the team operate?
An elegant design that the team cannot run reliably is worse than a simpler one done well.
You are not locked into one choice. A broker can enable several mechanisms at once, so you can start with a simpler one and add another later, or serve different client groups differently.
13The Configuration Model: JAAS, Brokers and Clients
You do not need to memorise settings to understand where each piece of authentication configuration lives.
JAAS in one paragraph
Kafka’s Java components use a standard called JAAS, the Java Authentication and Authorization Service, to describe how a login should be performed. A JAAS configuration names a login module, which is the code that performs the mechanism, and gives it options such as the user name and password or the location of a keytab. Kafka lets you supply this either as a separate file or as a property inside its usual configuration, and the property form is usually preferred because it keeps everything in one place and allows different settings per listener.
What the broker decides
Which listeners exist and their protocols
Each listener is mapped to one of the four security protocols, so the broker knows which doors require SASL.
Which mechanisms are enabled
The broker lists the SASL mechanisms it will accept. A client asking for any other mechanism is refused.
Its own login information
The broker needs its own identity for each mechanism, for example its Kerberos keytab, or its own credentials when it calls other brokers.
How credentials are checked
This can be the built-in checker for the mechanism or a custom handler that consults an outside store or provider.
How principals are named
Rules map authentication results to principal names used by permissions.
What the client decides
Security protocol
The client must choose the protocol matching the listener it connects to, such as SASL with TLS.
Mechanism
The client names the one mechanism it wants to use out of the broker’s enabled list.
Its own credentials
The client supplies its user name and secret, its keytab, or a way to get a token.
TLS trust
For encrypted connections, the client must trust the certificate authority that signed the broker’s certificate.
The building decides which entrances exist, which kinds of ID each one accepts, and how the guard verifies them. The visitor decides which entrance to approach, which ID to show and whether they trust the guard’s uniform. Both sides must agree or the visitor is turned away.
Assuming all client libraries use the same setting names. Libraries in languages other than Java often have their own properties for user name, password and mechanism, and may not use JAAS at all.
14Brokers Talk Too: Inter-Broker and Controller Authentication
Securing only client connections leaves the internal traffic between servers wide open. Kafka lets you protect that too.
Inter-broker traffic
Brokers constantly talk to each other, most importantly to replicate data from partition leaders to followers. Those connections pass through a listener, and the cluster is told which security protocol and which SASL mechanism to use for them. Each broker therefore needs its own credentials as a client of the other brokers, and the other brokers must recognise that identity and treat it as trusted for replication.
Controller communication
Kafka clusters have controllers that manage metadata such as topics and partition leadership. In clusters using Kafka’s own controller quorum, the controllers and brokers also communicate over listeners that can be secured with the same kinds of protocols and mechanisms. Older clusters that rely on an external coordination service need that service protected separately.
flowchart LR
APP["Applications"] -->|"Client listener, SASL_SSL"| B1["Broker 1"]
APP -->|"Client listener, SASL_SSL"| B2["Broker 2"]
B1 |"Inter-broker listener, authenticated"| B2
B1 |"Controller listener, authenticated"| CT["Controllers"]
B2 |"Controller listener, authenticated"| CT
A bank checks customers at the front door, but staff also use badge readers to move between the back offices and the vault. Guarding only the public entrance leaves the internal corridors open to anyone who slips through.
Permissions for the brokers themselves
Because brokers act on each other’s behalf, their principals need special rights in the access control rules, for example the right to replicate data and manage cluster metadata. When enabling authorization, remember to grant these rights to the broker identities before turning on enforcement, otherwise the cluster may stop replicating and become unstable.
Switching on strict permissions before granting the broker identities their internal rights can break replication and take the cluster down. Plan the order of changes carefully and test in a non-production environment first.
15Credential Lifecycle: Storage, Rotation and Re-Authentication
Getting authentication working is the easy half. Keeping credentials safe and fresh over months and years is the harder half.
Where secrets should live
Passwords and keys should not sit in plain text inside configuration files that are stored in shared repositories or copied between machines. Kafka supports external configuration providers that read secrets from protected files or directories at start-up, and many organisations connect these to a dedicated secrets manager. Dynamic broker settings that hold passwords can also be stored encrypted. The goal is that a copy of a configuration file alone does not reveal any secret.
Rotation without downtime
Credentials should be changed regularly and immediately after any suspected leak. For password mechanisms, a safe pattern is to create a new credential, roll it out to clients gradually, confirm nobody uses the old one, and then remove the old one. Mechanisms that support several credentials for the same user, or that use short-lived tokens, make this smoother. Rotation that requires changing everything at the same instant is risky.
Long-lived connections and re-authentication
As noted earlier, authentication happens when a connection is opened, and Kafka connections often last for days. Without further action, a client whose credential has been revoked, or whose token has expired, might carry on using the old connection. Kafka supports forcing re-authentication after a set interval, so the broker requires clients on long-lived connections to prove themselves again. Clients that can refresh credentials, such as those using tokens, then continue smoothly, and clients whose credentials were removed are disconnected at the next check.
flowchart LR
A["Client authenticates"] --> B["Connection stays open"]
B --> C{"Re-authentication interval reached?"}
C -- "No" --> B
C -- "Yes" --> D["Broker asks client to authenticate again"]
D --> E{"Credentials still valid?"}
E -- "Yes" --> B
E -- "No" --> F["Connection closed"]
A visitor badge that never expires is a security hole. Good buildings ask people to swipe again at each floor, or replace badges every day, so that a lost badge stops working quickly.
Keep secrets out of files
Use secret providers or managers, not plain text in shared configuration.
Rotate on a schedule
Change credentials regularly and after any suspected leak.
Overlap old and new
Roll out new credentials gradually before removing the old ones.
Force re-authentication
Set an interval so revoked credentials cannot live on inside open connections.
Removing a user from the credential store does not close their existing connections. Only re-authentication, or explicitly disconnecting the client, makes the removal take effect at once.
16Several Listeners, Several Mechanisms
A single cluster can serve different groups with different doors, each with its own rules.
flowchart TB
subgraph BR["Kafka broker"]
L1["Internal listener: SASL_SSL with SCRAM"]
L2["External listener: SASL_SSL with OAUTHBEARER"]
L3["Inter-broker listener: SASL_SSL with SCRAM"]
end
A["Internal applications"] --> L1
P["Partner and cloud applications"] --> L2
O["Other brokers"] --> L3
Why mix them
Internal and external audiences
Internal services may use a simple password mechanism, while external partners come through a listener requiring tokens from a partner-friendly identity provider.
Migration between mechanisms
During a move from one mechanism to another, both can be enabled on the same listener, so clients switch one by one without a shared cut-over moment.
Different network zones
A listener reachable only inside a locked-down network can carry a lighter setup than one exposed to the wider internet.
Legacy clients
Older applications that only support a certain mechanism can be served by a dedicated listener, while modern clients use a better one.
A large campus has a staff entrance with badge readers, a visitor entrance with a reception desk, and a service gate for delivery vans. Each has its own checks, but all lead into the same buildings.
Advertising the wrong listener address to clients. Clients are told which addresses to use after their first connection, and if the advertised address points to a different listener than intended, they may connect with the wrong protocol and fail in confusing ways.
17Rolling Out SASL on a Running Cluster
Most teams add authentication to a cluster that is already serving traffic. Doing it safely means changing things in the right order.
flowchart TD
A["Stage 1: Inventory clients and their libraries"] --> B["Stage 2: Add a new SASL_SSL listener beside the existing one"]
B --> C["Stage 3: Create an identity for each application"]
C --> D["Stage 4: Migrate clients one by one to the new listener"]
D --> E["Stage 5: Move inter-broker traffic to the secured listener"]
E --> F["Stage 6: Remove the old open listener"]
F --> G["Stage 7: Turn on authorization and monitoring"]
Take stock of clients
List every application, connector and tool that connects, which library and version each uses, and who owns it. Unknown clients are the biggest risk during migration.
Add the secured listener alongside the old one
Configure a new listener with the chosen protocol and mechanism while leaving the existing listener in place. Brokers are updated in a rolling fashion, one at a time.
Create identities and credentials
Give each application its own principal, and deliver its credential through your secrets process, not by email or chat.
Migrate clients gradually
Switch each application to the new listener, test that it works, and watch for errors before moving on to the next one.
Secure inter-broker traffic
Move replication and controller traffic to a secured listener, again with a rolling restart and close monitoring.
Close the old door
Once metrics show no traffic on the open listener, remove it. Check network rules too, so it cannot be reached by accident.
Add permissions, monitoring and audits
Turn on authorization with rules based on the new principals, grant broker rights first, and set alerts on failed authentications.
To add security guards to a building that people use every day, you first open a new, guarded entrance, move each tenant to it one at a time, and only then lock the old, unguarded door. You never lock everyone out at once.
Give application teams a clear deadline, working examples and a place to ask for help. Most delays in a rollout come from clients nobody knew about, or teams who cannot easily change their configuration.
18The Wider Ecosystem: Connect, Streams, Schema Registry and Tools
Kafka’s brokers are only the centre. Every companion program also needs to authenticate, and each has its own place for settings.
Producers and consumers
Regular client applications carry authentication settings in their client configuration, and the same identity is used for all their connections.
Kafka Streams applications
Streams applications are clients underneath, so they use the same client settings. Because they also create internal topics, their identity needs rights to create and use those topics.
Kafka Connect
Connect workers need credentials for their own connection to Kafka, and separately for the internal topics they use. Each connector may also need its own overrides for producing or consuming, so that different connectors run with different identities and limited rights.
Schema registry and other services
Services that store their data in Kafka, such as a schema registry, connect as clients and need identities with rights to their own topics. They also have separate authentication for their own web interfaces.
Replication and mirroring tools
Tools that copy data between clusters need credentials for both the source and the target, often with different mechanisms.
Administration and command-line tools
Administrators use tools that also need client settings, usually stored in a small properties file. Guard these files because they often carry powerful credentials.
Monitoring agents
Monitoring systems that read metrics or consumer positions need read-only identities, never full administrative ones.
Every contractor working in the building, the cleaner, the electrician, the auditor, needs a badge. Giving them all the master badge is convenient but dangerous. A badge that opens only the rooms they need for their job is safer.
Using the administrator credential for convenience in connectors and monitoring tools. A leak from any one of these tools then gives an attacker full control of the cluster.
19Security Around Authentication
Authentication is one layer in a stack. These neighbouring practices decide how much protection it actually gives.
Always pair with TLS on untrusted networks
TLS hides the data, protects password mechanisms from eavesdroppers and lets clients verify they are talking to the real broker. Clients should check the broker’s certificate and its host name.
Follow authentication with authorization
Use access control rules so that each principal can do only what its job requires. Grant read on the topics it consumes and write on the topics it produces, and nothing more.
One identity per application
Individual identities allow precise permissions, meaningful logs and safe rotation, so a single leak does not force a company-wide change.
Protect the credential store
Whether credentials live in Kafka metadata, a directory, an identity provider or a secrets manager, that store is as sensitive as the cluster itself and should have its own tight access rules and backups.
Limit the network surface
Use firewalls and private networks so only intended clients can even reach the listeners. Authentication then works as a second barrier, not the only one.
Set quotas per principal
Rate limits for bandwidth and requests protect the cluster from a misbehaving or compromised client, and depend on identities being distinct.
Keep software up to date
Security fixes for Kafka, its client libraries and the Java runtime matter. Old versions may lack mechanisms, or contain known weaknesses in authentication code.
A secure building has a fence, a guarded gate, badges, room-level locks, cameras and a visitor log. Removing any one layer is not fatal, but each one makes the whole safer.
20Monitoring and Auditing Authentication
If nobody watches the door, nobody notices when it is being tested. A few signals give good visibility.
| Signal | What It Tells You | Typical Response |
|---|---|---|
| Failed authentication count | Wrong credentials, misconfiguration or an attack | Identify the source, check whether it is one client or many |
| Successful authentication count | Normal activity and its baseline | Watch for sudden drops or spikes |
| Failed re-authentication count | Expired or revoked credentials on long connections | Check token refresh or credential removal |
| Connection creation rate | Clients reconnecting in loops | Look for bad credentials causing retry storms |
| Authentication errors in broker logs | Details of the reason for failure | Read the error and fix the client or broker setting |
| Principals in use | Who is actually connecting | Compare against the list of expected applications |
| Credential expiry dates | Upcoming outages from expired secrets | Alert well before expiry |
| Changes to credentials and mechanisms | Administrative activity | Audit who changed what and when |
Alerts worth having
Alert on a sudden rise in failed authentications, on a client that fails repeatedly from a new address, on credentials approaching their expiry date, on new principals appearing that nobody expected, and on any weakening of security settings such as enabling a new mechanism or a plain listener.
Audit logs
Keep logs that record which principal connected from where, and which administrative actions were taken. Send them to a central logging system with restricted access, so that they survive incidents and cannot be quietly edited by the people they describe.
A guard who logs every entry and every refused attempt can notice when the same stranger tries several doors, or when a former employee’s badge is suddenly used at night. Without the log, these events are invisible.
21Troubleshooting Common Failures
Most authentication problems fall into a small number of familiar patterns.
| Symptom | Likely Cause | What to Check |
|---|---|---|
| Error saying the mechanism is not enabled, with a list of enabled ones | Client and broker disagree on the mechanism | Client mechanism setting versus broker enabled list for that listener |
| Authentication failed, invalid credentials | Wrong user name or password, or the user was not created | Credential store, spelling, and whether the right environment is used |
| Client hangs or times out during connection | Client using SASL against a plain listener, or the reverse | Security protocol setting and the listener’s port |
| TLS certificate errors before SASL starts | Broker certificate not trusted, or host name mismatch | Trust store, certificate chain and advertised host names |
| Kerberos tickets rejected | Clock drift, DNS mismatch or wrong service name | Time synchronisation, reverse and forward DNS, service name setting |
| Token rejected | Token expired, wrong audience or issuer, keys not fetched | Token contents, provider endpoints and broker validation settings |
| Works from one broker, fails from another | Inconsistent configuration across brokers | Compare broker configuration and rolling update state |
| Authenticated but denied actions | Missing permissions for the principal | Access control rules and the exact principal name |
| Cluster instability after enabling security | Broker identities lack internal rights | Inter-broker mechanism and permissions for broker principals |
A calm method for diagnosis
Read the exact error
Authentication errors are often specific. The message usually states the mechanism, the reason or the list of enabled options.
Confirm the listener and protocol
Make sure the client is pointed at the intended listener and uses the matching security protocol.
Check the channel first
If TLS is used, resolve certificate problems before looking at SASL, since SASL only starts after TLS succeeds.
Verify credentials with a minimal client
Use a simple command-line client with the same settings to separate application bugs from configuration problems.
Look at the broker log
The broker’s log often shows the reason for a refusal that the client only sees as a generic failure.
Authentication failure and authorization failure look different. Failing to connect at all points to authentication or transport. Connecting fine but being refused for a topic points to permissions.
22Design Patterns and Anti-Patterns
Habits that keep authentication healthy, and traps that quietly weaken it.
Patterns worth adopting
SASL over TLS everywhere outside test labs
Make the encrypted, authenticated listener the standard for every environment that holds real data.
One identity per application and environment
Separate identities for test and production, and for each application, with permissions scoped to what each really needs.
Automated credential delivery and rotation
Use a secrets manager to issue and rotate credentials, so humans never type or paste production secrets.
Short lifetimes where possible
Prefer mechanisms and settings that keep credentials short-lived and force periodic re-authentication.
Anti-patterns to avoid
Problem
Running PLAIN authentication over an unencrypted listener on a shared network.
Why It’s Harmful
Passwords cross the network in readable form. Anyone able to capture traffic can steal them and impersonate the application.
Correct Approach
Use SASL with TLS, or a mechanism that never sends the password, and encrypt the channel anyway.
Problem
One shared administrator credential used by every application, script and tool.
Why It’s Harmful
Any leak gives full control. Logs cannot tell who did what, and rotating the secret means changing everything at once.
Correct Approach
Create separate identities with narrow permissions, and reserve administrator rights for a few controlled accounts.
Problem
Storing secrets in plain text in configuration files kept in shared code repositories.
Why It’s Harmful
Anyone with repository access, now or in the future, can read production credentials. They remain in the history even after deletion.
Correct Approach
Reference secrets through configuration providers or a secrets manager, and keep only references in the repository.
Problem
Leaving the old open listener running after the secured one has been introduced.
Why It’s Harmful
Anyone can still bypass authentication by connecting to the open door, making the whole effort meaningless.
Correct Approach
Migrate all clients, verify no traffic remains, then remove the old listener and block its port at the network level.
Problem
Using the development-grade unsecured token handler for OAUTHBEARER in production.
Why It’s Harmful
Tokens are accepted without proper signature and expiry checks, so anyone can craft a token and claim any identity.
Correct Approach
Use a properly validating handler tied to a real identity provider and its published signing keys.
23Best Practices and Common Mistakes
A checklist to keep beside you when designing or reviewing Kafka authentication.
Best Practices
- Use SASL_SSL for every listener that carries real data
- Choose the mechanism that fits your existing identity system
- Give each application its own principal
- Keep secrets in a secrets manager, not in plain files
- Rotate credentials on a schedule and after any incident
- Force re-authentication on long-lived connections
- Secure inter-broker and controller traffic too
- Follow authentication with permission rules
- Monitor failed logins and credential expiry dates
Common Mistakes
- Thinking SASL alone secures the cluster
- Sending passwords over unencrypted connections
- Sharing one credential across many applications
- Leaving an open listener running
- Ignoring credential expiry until an outage happens
- Enabling strict permissions before granting broker rights
- Mixing up client library setting names across languages
- Using development token handlers in production
- Giving monitoring and connector tools admin rights
Authentication proves who is connecting. It is only one gate. Encryption, permissions, network limits, monitoring and disciplined credential handling together decide how safe the cluster really is.
A strong front door lock does not help if the spare key sits under the doormat, the windows are open, and nobody notices who comes and goes. Real safety is a set of habits, not a single device.
24Real-World Scenarios
Five common situations show how the choices fit together in practice.
Scenario 1: A mid-sized company running its own cluster
A team without Kerberos or a central token service picks SCRAM over TLS. Each application has its own user, created with the administration tools, and secrets are delivered from a secrets manager. Re-authentication is set to a few hours, and permissions are granted per topic.
Scenario 2: A large enterprise with Kerberos everywhere
The organisation already issues Kerberos identities to services. Brokers and applications use GSSAPI with keytabs delivered by an automated process, and name mapping rules produce simple principal names. Clock synchronisation and DNS are monitored closely, because they are the most common cause of failures.
Scenario 3: A cloud-native platform using tokens
Applications run in containers and obtain short-lived tokens from the company’s identity provider using their platform identity. Brokers validate tokens against the provider’s signing keys. No long-lived secret is stored in any application image.
Scenario 4: Serving partners and internal teams together
Internal applications use one listener with SCRAM, while partner companies connect through a separate listener that requires tokens from a federated identity provider. Quotas per principal keep any one partner from overloading the cluster.
Scenario 5: Securing a legacy open cluster
A team discovers that a growing cluster has no authentication. They inventory clients, add a secured listener, migrate applications team by team, move replication to the secured listener, close the open port and only then add permissions, with monitoring throughout.
| Scenario | Mechanism | Key Concern |
|---|---|---|
| Mid-sized self-managed | SCRAM over TLS | Secret delivery and rotation |
| Kerberos enterprise | GSSAPI | DNS, clocks and keytab handling |
| Cloud-native platform | OAUTHBEARER | Token validation and refresh |
| Partners plus internal | Different mechanisms per listener | Separation and quotas |
| Legacy open cluster | Staged migration | Unknown clients and ordering of steps |
25Frequently Asked Questions
No. SASL is a framework. It defines how authentication messages are exchanged, and specific mechanisms such as PLAIN, SCRAM, GSSAPI and OAUTHBEARER do the actual proving of identity.
Not by itself in Kafka. Encryption comes from TLS. That is why the combination SASL_SSL is the common choice, since it gives both encryption and identity checking.
Yes, with TLS, and often with credentials checked against an external store. It is simple and widely supported. Without TLS, it exposes passwords and should not be used across untrusted networks.
PLAIN sends the password to the broker. SCRAM proves knowledge of the password through a challenge and response calculation and stores only salted verification data. SCRAM is generally the better password-based choice.
Both work. Choose mutual TLS if you already have strong certificate management. Choose SASL if you prefer passwords, tickets or tokens tied to an existing identity system. They can also be combined, with TLS for the channel and SASL for identity.
It is the identity the broker assigns to a connection after successful authentication. Permissions, quotas and logs are all based on it.
Yes. Several mechanisms can be enabled on the same listener, and each client chooses one. This is useful during migrations and for mixed client populations.
The existing connection may continue until it closes or is forced to re-authenticate. Setting a re-authentication interval makes removals take effect within a bounded time.
If you want the internal traffic protected, yes. Configure a secured listener and a mechanism for inter-broker communication, and give the broker identities the internal rights they need.
A common cause is a protocol mismatch, such as a SASL client connecting to a listener that expects plain traffic or the reverse. Check the security protocol and the port.
Use external configuration providers or a secrets manager so that configuration files hold only references. Restrict file permissions, avoid committing secrets to repositories, and rotate them regularly.
No. Authentication only establishes who the client is. Authorization, through access control rules, decides which actions that identity may perform.
26Summary and Key Takeaways
An unprotected Kafka cluster accepts connections from anyone, so authentication is the first gate of a secure platform. SASL is the framework Kafka uses to let clients prove who they are, using mechanisms such as PLAIN, SCRAM, GSSAPI with Kerberos and OAUTHBEARER. Each connection performs a short handshake, and on success the broker records a principal that drives permissions, quotas and audit logs. Good designs pair SASL with TLS, follow it with authorization, give every application its own identity and handle credentials with care.
Success depends as much on operations as on settings: staged rollouts, secret storage, rotation, re-authentication, monitoring and quick troubleshooting. If you remember one sentence, let it be this: SASL tells Kafka who is knocking, but only encryption, permissions and disciplined credential habits make the door truly secure.
Key Takeaways
- Authentication is separate from authorization and encryption — SASL proves identity, access rules decide permissions and TLS protects the channel, and all three are needed.
- SASL is a framework with mechanisms — PLAIN, SCRAM, GSSAPI and OAUTHBEARER differ in how identity is proven, and cloud platforms may add their own.
- Use SASL_SSL in production — PLAIN especially must never travel over an unencrypted connection, and SCRAM and others still benefit from TLS.
- The principal is the key result — every permission, quota and log entry depends on the identity created at login, so give each application its own.
- Pick the mechanism that fits your identity system — SCRAM for simple self-managed clusters, GSSAPI where Kerberos exists, OAUTHBEARER with a central token provider, and several can coexist.
- Secure the whole platform — protect inter-broker and controller traffic, companion services and administration tools, not only application clients.
- Manage the credential lifecycle — store secrets safely, rotate them, force re-authentication, roll out in stages, close old open listeners and monitor failures and expiry dates.