最近需要对接一些告警数据需要用kafka SASL_PLAINTEXT 认证,之前没用过kafka 查了很多资料最后终于搞定了 记录分享一下。

1. 安装 Kafka 及依赖项c

  • 确保已经安装了 Kafka 3.8.0 及其依赖项,例如 Java 运行时环境(JRE)。

2. 编辑 Kafka 配置文件

  • Kafka 的主要配置文件是 server.properties,位于 Kafka 安装目录下的 config/ 文件夹中
配置 broker(Kafka 服务端)
  • 打开 config/server.properties 并进行以下修改:
# 设置监听器(允许 SASL_PLAINTEXT 协议)
listeners=SASL_PLAINTEXT://:9092
# 如果你有其他协议,也可以加上PLAINTEXT监听器
# listeners=SASL_PLAINTEXT://:9092,PLAINTEXT://:9093

#以下是新增的
#定义 broker 之间通信的协议
inter.broker.listener.name=SASL_PLAINTEXT
#SASL机制
sasl.enabled.mechanisms=PLAIN
# Kafka broker 间使用的 SASL 机制
sasl.mechanism.inter.broker.protocol=PLAIN

# 配置 JAAS(Java Authentication and Authorization Service)
listener.name.sasl_plaintext.plain.sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required \
   username="admin" \
   password="admin-secret" \
   user_admin="admin-secret" \
   user_alice="alice-secret"; 
 # 指定 Kafka broker 的 JAAS 配置文件路径
java.security.auth.login.config=kafka安装目录/config/kafka_server_jaas.conf

3. 创建 JAAS 配置文件(kafka_server_jaas.conf)

  • 在 Windows 中,你需要创建一个独立的 JAAS 配置文件来定义 Kafka 服务端的认证信息。
    在 kafka安装目录/config/目录下创建一个文件,命名为 kafka_server_jaas.conf,内容如下:
KafkaServer {
   org.apache.kafka.common.security.plain.PlainLoginModule required
   username="admin"
   password="admin-secret"
   user_admin="admin-secret"
   user_alice="alice-secret";
};

4. 配置 Zookeeper

  • 编辑 zookeeper.properties 文件:
authProvider.1=org.apache.zookeeper.server.auth.SASLAuthenticationProvider
requireClientAuthScheme=sasl
jaasLoginRenew=3600000

5. 配置客户端(producer.properties与consumer.properties)

  • 为了让 Kafka 客户端(生产者和消费者)能够通过 SASL_PLAINTEXT 认证连接 Kafka broker,客户端也需要相应的配置。
security.protocol=SASL_PLAINTEXT
sasl.mechanism=PLAIN
sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required \
username="alice" \
password="alice-secret";

6. 启动 Kafka 和 Zookeeper

  1. 启动 Zookeeper:
bin\windows\zookeeper-server-start.bat config\zookeeper.properties
  1. 启动 Kafka:
bin\windows\kafka-server-start.bat config\server.properties

7. 测试生产者和消费者

  • 启动生产者:
bin\windows\kafka-console-producer.bat --broker-list localhost:9092 --topic test-topic --producer.config ../../config/producer.properties
  • 启动消费者:
bin\windows\kafka-console-consumer.bat --bootstrap-server localhost:9092 --topic test-topic --consumer.config ../../config/consumer.properties --from-beginning

8. 测试和验证

  • 启动生产者和消费者,测试是否能够正常通过 SASL_PLAINTEXT 连接并进行身份验证。

用kafka tool 测试连接

  1. 第一步 add new addConnection
    在这里插入图片描述

  2. 第二步 security 选择 SASL Plaintext
    在这里插入图片描述

  3. 第三步 Advanced

  • Bootstrap servers 填自己的kafka服务地址与ip
  • SASL Mechanism输入: PLAIN
    在这里插入图片描述
  1. 第四步 JAAS config
  • 输入客户端中配置的用户名密码内容
org.apache.kafka.common.security.plain.PlainLoginModule required 
username="alice" 
password="alice-secret";

在这里插入图片描述

点击 test测试连通性 并完成保存!

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐