0


kafka权限认证 topic权限认证 权限动态认证-亲测成功

kafka权限认证 topic权限认证 权限动态认证-亲测成功

kafka动态认证 自定义认证 安全认证-亲测成功

MacBook Linux安装Kafka

Linux解压安装Kafka

介绍

1、Kafka的权限分类

  • 身份认证(Authentication):对client 与服务器的连接进行身份认证,brokers和zookeeper之间的连接进行Authentication(producer 和 consumer)、其他 brokers、tools与 brokers 之间连接的认证。上一篇博文介绍了连接的身份认证。
  • 权限控制(Authorization):实现对于消息级别的权限控制,clients的读写操作进行Authorization:(生产/消费/group)数据权限。这节我们讲解Topic权限的控制。

kafka配置自定义权限认证

修改配置文件,在kafka主目录下,D:\kafka_2.12-3.5.0\config\server.properties

  1. enable_db_acl = true
  2. authorizer.class.name=com.liang.kafka.auth.handler.MyAclAuthorizer
  3. super.users=admin;liang
  4. druid.name = mysql_db
  5. druid.type = com.alibaba.druid.pool.DruidDataSource
  6. druid.url = jdbc:mysql://127.0.0.1:3306/test?useSSL=FALSE&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=Asia/Shanghai
  7. druid.username = root
  8. druid.password = root
  9. druid.filters = stat
  10. druid.driverClassName = com.mysql.cj.jdbc.Driver
  11. druid.initialSize = 5
  12. druid.minIdle = 2
  13. druid.maxActive = 50
  14. druid.maxWait = 60000
  15. druid.timeBetweenEvictionRunsMillis = 60000
  16. druid.minEvictableIdleTimeMillis = 300000
  17. druid.validationQuery = SELECT 'x'
  18. druid.testWhileIdle = true
  19. druid.testOnBorrow = false
  20. druid.poolPreparedStatements = false
  21. druid.maxPoolPreparedStatementPerConnectionSize = 20

其中:

  • enable_db_acl用来控制是否开启动态权限认证。
  • authorizer.class.name配置自定义权限的类

windows完整配置如下:

  1. # Licensed to the Apache Software Foundation (ASF) under one or more
  2. # contributor license agreements. See the NOTICE file distributed with
  3. # this work for additional information regarding copyright ownership.
  4. # The ASF licenses this file to You under the Apache License, Version 2.0
  5. # (the "License"); you may not use this file except in compliance with
  6. # the License. You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # This configuration file is intended for use in ZK-based mode, where Apache ZooKeeper is required.
  17. # See kafka.server.KafkaConfig for additional details and defaults
  18. #
  19. ############################# Server Basics #############################
  20. # The id of the broker. This must be set to a unique integer for each broker.
  21. broker.id=0
  22. ############################# Socket Server Settings #############################
  23. # The address the socket server listens on. If not configured, the host name will be equal to the value of
  24. # java.net.InetAddress.getCanonicalHostName(), with PLAINTEXT listener name, and port 9092.
  25. # FORMAT:
  26. # listeners = listener_name://host_name:port
  27. # EXAMPLE:
  28. # listeners = PLAINTEXT://your.host.name:9092
  29. #listeners=PLAINTEXT://:9092
  30. # Listener name, hostname and port the broker will advertise to clients.
  31. # If not set, it uses the value for "listeners".
  32. #advertised.listeners=PLAINTEXT://your.host.name:9092
  33. advertised.listeners=SASL_PLAINTEXT://localhost:9092
  34. # Maps listener names to security protocols, the default is for them to be the same. See the config documentation for more details
  35. #listener.security.protocol.map=PLAINTEXT:PLAINTEXT,SSL:SSL,SASL_PLAINTEXT:SASL_PLAINTEXT,SASL_SSL:SASL_SSL
  36. sasl.enabled.mechanisms = PLAIN
  37. sasl.mechanism.inter.broker.protocol = PLAIN
  38. security.inter.broker.protocol = SASL_PLAINTEXT
  39. listeners = SASL_PLAINTEXT://localhost:9092
  40. enable_db_acl = true
  41. authorizer.class.name=com.liang.kafka.auth.handler.MyAclAuthorizer
  42. super.users=admin;liang
  43. enable_db_auth = true
  44. listener.name.sasl_plaintext.plain.sasl.server.callback.handler.class=com.liang.kafka.auth.handler.MyPlainServerCallbackHandler
  45. druid.name = mysql_db
  46. druid.type = com.alibaba.druid.pool.DruidDataSource
  47. druid.url = jdbc:mysql://127.0.0.1:3306/testdb?useSSL=FALSE&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=Asia/Shanghai
  48. druid.topic.url = jdbc:mysql://127.0.0.1:3306/topicdb?useSSL=FALSE&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=Asia/Shanghai
  49. druid.username = root
  50. druid.password = root
  51. druid.filters = stat
  52. druid.driverClassName = com.mysql.cj.jdbc.Driver
  53. druid.initialSize = 5
  54. druid.minIdle = 2
  55. druid.maxActive = 50
  56. druid.maxWait = 60000
  57. druid.timeBetweenEvictionRunsMillis = 60000
  58. druid.minEvictableIdleTimeMillis = 300000
  59. druid.validationQuery = SELECT 'x'
  60. druid.testWhileIdle = true
  61. druid.testOnBorrow = false
  62. druid.poolPreparedStatements = false
  63. druid.maxPoolPreparedStatementPerConnectionSize = 20
  64. # The number of threads that the server uses for receiving requests from the network and sending responses to the network
  65. num.network.threads=3
  66. # The number of threads that the server uses for processing requests, which may include disk I/O
  67. num.io.threads=8
  68. # The send buffer (SO_SNDBUF) used by the socket server
  69. socket.send.buffer.bytes=102400
  70. # The receive buffer (SO_RCVBUF) used by the socket server
  71. socket.receive.buffer.bytes=102400
  72. # The maximum size of a request that the socket server will accept (protection against OOM)
  73. socket.request.max.bytes=104857600
  74. ############################# Log Basics #############################
  75. # A comma separated list of directories under which to store log files
  76. log.dirs=D:\kafka_2.12-3.5.0\kafka-logs
  77. # The default number of log partitions per topic. More partitions allow greater
  78. # parallelism for consumption, but this will also result in more files across
  79. # the brokers.
  80. num.partitions=1
  81. # The number of threads per data directory to be used for log recovery at startup and flushing at shutdown.
  82. # This value is recommended to be increased for installations with data dirs located in RAID array.
  83. num.recovery.threads.per.data.dir=1
  84. ############################# Internal Topic Settings #############################
  85. # The replication factor for the group metadata internal topics "__consumer_offsets" and "__transaction_state"
  86. # For anything other than development testing, a value greater than 1 is recommended to ensure availability such as 3.
  87. offsets.topic.replication.factor=1
  88. transaction.state.log.replication.factor=1
  89. transaction.state.log.min.isr=1
  90. ############################# Log Flush Policy #############################
  91. # Messages are immediately written to the filesystem but by default we only fsync() to sync
  92. # the OS cache lazily. The following configurations control the flush of data to disk.
  93. # There are a few important trade-offs here:
  94. # 1. Durability: Unflushed data may be lost if you are not using replication.
  95. # 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush.
  96. # 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to excessive seeks.
  97. # The settings below allow one to configure the flush policy to flush data after a period of time or
  98. # every N messages (or both). This can be done globally and overridden on a per-topic basis.
  99. # The number of messages to accept before forcing a flush of data to disk
  100. #log.flush.interval.messages=10000
  101. # The maximum amount of time a message can sit in a log before we force a flush
  102. #log.flush.interval.ms=1000
  103. ############################# Log Retention Policy #############################
  104. # The following configurations control the disposal of log segments. The policy can
  105. # be set to delete segments after a period of time, or after a given size has accumulated.
  106. # A segment will be deleted whenever *either* of these criteria are met. Deletion always happens
  107. # from the end of the log.
  108. # The minimum age of a log file to be eligible for deletion due to age
  109. log.retention.hours=168
  110. # A size-based retention policy for logs. Segments are pruned from the log unless the remaining
  111. # segments drop below log.retention.bytes. Functions independently of log.retention.hours.
  112. #log.retention.bytes=1073741824
  113. # The maximum size of a log segment file. When this size is reached a new log segment will be created.
  114. #log.segment.bytes=1073741824
  115. # The interval at which log segments are checked to see if they can be deleted according
  116. # to the retention policies
  117. log.retention.check.interval.ms=300000
  118. ############################# Zookeeper #############################
  119. # Zookeeper connection string (see zookeeper docs for details).
  120. # This is a comma separated host:port pairs, each corresponding to a zk
  121. # server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002".
  122. # You can also append an optional chroot string to the urls to specify the
  123. # root directory for all kafka znodes.
  124. zookeeper.connect=localhost:2181
  125. # Timeout in ms for connecting to zookeeper
  126. zookeeper.connection.timeout.ms=18000
  127. ############################# Group Coordinator Settings #############################
  128. # The following configuration specifies the time, in milliseconds, that the GroupCoordinator will delay the initial consumer rebalance.
  129. # The rebalance will be further delayed by the value of group.initial.rebalance.delay.ms as new members join the group, up to a maximum of max.poll.interval.ms.
  130. # The default value for this is 3 seconds.
  131. # We override this to 0 here as it makes for a better out-of-the-box experience for development and testing.
  132. # However, in production environments the default value of 3 seconds is more suitable as this will help to avoid unnecessary, and potentially expensive, rebalances during application startup.
  133. group.initial.rebalance.delay.ms=0

Linux下完整配置如下

  1. # Licensed to the Apache Software Foundation (ASF) under one or more
  2. # contributor license agreements. See the NOTICE file distributed with
  3. # this work for additional information regarding copyright ownership.
  4. # The ASF licenses this file to You under the Apache License, Version 2.0
  5. # (the "License"); you may not use this file except in compliance with
  6. # the License. You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # see kafka.server.KafkaConfig for additional details and defaults
  16. ############################# Server Basics #############################
  17. # The id of the broker. This must be set to a unique integer for each broker.
  18. broker.id = 999
  19. ############################# Socket Server Settings #############################
  20. # The address the socket server listens on. It will get the value returned from
  21. # java.net.InetAddress.getCanonicalHostName() if not configured.
  22. # FORMAT:
  23. # listeners = listener_name://host_name:port
  24. # EXAMPLE:
  25. # listeners = PLAINTEXT://your.host.name:9092
  26. # listeners=PRIVATE://:9092,PUBLIC://:9093
  27. sasl.enabled.mechanisms = PLAIN
  28. sasl.mechanism.inter.broker.protocol = PLAIN
  29. security.inter.broker.protocol = SASL_PLAINTEXT
  30. listeners = SASL_PLAINTEXT://:9092
  31. enable_db_acl = true
  32. authorizer.class.name=com.liang.kafka.auth.handler.MyAclAuthorizer
  33. super.users=admin;liang
  34. enable_db_auth = true
  35. listener.name.sasl_plaintext.plain.sasl.server.callback.handler.class=com.liang.kafka.auth.handler.MyPlainServerCallbackHandler
  36. druid.name = mysql_db
  37. druid.type = com.alibaba.druid.pool.DruidDataSource
  38. druid.url = jdbc:mysql://192.168.1.77:3306/testdb?useSSL=FALSE&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=Asia/Shanghai
  39. druid.topic.url = jdbc:mysql://192.168.1.77:3306/topicdb?useSSL=FALSE&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=Asia/Shanghai
  40. druid.username = root
  41. druid.password = root
  42. druid.filters = stat
  43. druid.driverClassName = com.mysql.cj.jdbc.Driver
  44. druid.initialSize = 5
  45. druid.minIdle = 2
  46. druid.maxActive = 50
  47. druid.maxWait = 60000
  48. druid.timeBetweenEvictionRunsMillis = 60000
  49. druid.minEvictableIdleTimeMillis = 300000
  50. druid.validationQuery = SELECT 'x'
  51. druid.testWhileIdle = true
  52. druid.testOnBorrow = false
  53. druid.poolPreparedStatements = false
  54. druid.maxPoolPreparedStatementPerConnectionSize = 20
  55. # Hostname and port the broker will advertise to producers and consumers. If not set,
  56. # it uses the value for "listeners" if configured. Otherwise, it will use the value
  57. # returned from java.net.InetAddress.getCanonicalHostName().
  58. advertised.listeners = SASL_PLAINTEXT://192.168.1.77:10092
  59. # Maps listener names to security protocols, the default is for them to be the same. See the config documentation for more details
  60. # The number of threads that the server uses for receiving requests from the network and sending responses to the network
  61. num.network.threads=3
  62. # The number of threads that the server uses for processing requests, which may include disk I/O
  63. num.io.threads=8
  64. # The send buffer (SO_SNDBUF) used by the socket server
  65. socket.send.buffer.bytes=102400
  66. # The receive buffer (SO_RCVBUF) used by the socket server
  67. socket.receive.buffer.bytes=102400
  68. # The maximum size of a request that the socket server will accept (protection against OOM)
  69. socket.request.max.bytes=104857600
  70. ############################# Log Basics #############################
  71. # A comma separated list of directories under which to store log files
  72. log.dirs=/opt/kafka/kafka-logs
  73. # The default number of log partitions per topic. More partitions allow greater
  74. # parallelism for consumption, but this will also result in more files across
  75. # the brokers.
  76. num.partitions=1
  77. # The number of threads per data directory to be used for log recovery at startup and flushing at shutdown.
  78. # This value is recommended to be increased for installations with data dirs located in RAID array.
  79. num.recovery.threads.per.data.dir=1
  80. ############################# Internal Topic Settings #############################
  81. # The replication factor for the group metadata internal topics "__consumer_offsets" and "__transaction_state"
  82. # For anything other than development testing, a value greater than 1 is recommended to ensure availability such as 3.
  83. offsets.topic.replication.factor=1
  84. transaction.state.log.replication.factor=1
  85. transaction.state.log.min.isr=1
  86. ############################# Log Flush Policy #############################
  87. # Messages are immediately written to the filesystem but by default we only fsync() to sync
  88. # the OS cache lazily. The following configurations control the flush of data to disk.
  89. # There are a few important trade-offs here:
  90. # 1. Durability: Unflushed data may be lost if you are not using replication.
  91. # 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush.
  92. # 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to excessive seeks.
  93. # The settings below allow one to configure the flush policy to flush data after a period of time or
  94. # every N messages (or both). This can be done globally and overridden on a per-topic basis.
  95. # The number of messages to accept before forcing a flush of data to disk
  96. #log.flush.interval.messages=10000
  97. # The maximum amount of time a message can sit in a log before we force a flush
  98. #log.flush.interval.ms=1000
  99. ############################# Log Retention Policy #############################
  100. # The following configurations control the disposal of log segments. The policy can
  101. # be set to delete segments after a period of time, or after a given size has accumulated.
  102. # A segment will be deleted whenever *either* of these criteria are met. Deletion always happens
  103. # from the end of the log.
  104. # The minimum age of a log file to be eligible for deletion due to age
  105. log.retention.hours=168
  106. # A size-based retention policy for logs. Segments are pruned from the log unless the remaining
  107. # segments drop below log.retention.bytes. Functions independently of log.retention.hours.
  108. #log.retention.bytes=1073741824
  109. # The maximum size of a log segment file. When this size is reached a new log segment will be created.
  110. log.segment.bytes=1073741824
  111. # The interval at which log segments are checked to see if they can be deleted according
  112. # to the retention policies
  113. log.retention.check.interval.ms=300000
  114. ############################# Zookeeper #############################
  115. # Zookeeper connection string (see zookeeper docs for details).
  116. # This is a comma separated host:port pairs, each corresponding to a zk
  117. # server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002".
  118. # You can also append an optional chroot string to the urls to specify the
  119. # root directory for all kafka znodes.
  120. zookeeper.connect=127.0.0.1:2181
  121. # Timeout in ms for connecting to zookeeper
  122. zookeeper.connection.timeout.ms=18000
  123. ############################# Group Coordinator Settings #############################
  124. # The following configuration specifies the time, in milliseconds, that the GroupCoordinator will delay the initial consumer rebalance.
  125. # The rebalance will be further delayed by the value of group.initial.rebalance.delay.ms as new members join the group, up to a maximum of max.poll.interval.ms.
  126. # The default value for this is 3 seconds.
  127. # We override this to 0 here as it makes for a better out-of-the-box experience for development and testing.
  128. # However, in production environments the default value of 3 seconds is more suitable as this will help to avoid unnecessary, and potentially expensive, rebalances during application startup.
  129. group.initial.rebalance.delay.ms=0
自定义实现topic权限认证

用户查询,订阅或发送topic时,判断是否有此topic的权限,订阅时有没有订阅分组的权限等。

maven项目引入相关的依赖包,pom添加如下依赖包

  1. <dependency><groupId>org.apache.kafka</groupId><artifactId>kafka_2.13</artifactId><version>2.8.1</version></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-cache</artifactId><version>5.7.21</version></dependency>

动态topic权限认证完整代码如下:

  1. packagecom.liang.kafka.auth.handler;importcn.hutool.core.collection.CollUtil;importcom.alibaba.druid.pool.DruidDataSource;importcom.liang.kafka.auth.cache.LocalCache;importcom.liang.kafka.auth.util.DataSourceUtil;importorg.apache.kafka.common.Endpoint;importorg.apache.kafka.common.acl.AclBinding;importorg.apache.kafka.common.acl.AclBindingFilter;importorg.apache.kafka.common.acl.AclOperation;importorg.apache.kafka.common.resource.PatternType;importorg.apache.kafka.common.resource.ResourcePattern;importorg.apache.kafka.common.resource.ResourceType;importorg.apache.kafka.server.authorizer.*;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importjava.io.IOException;importjava.sql.Connection;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.util.*;importjava.util.concurrent.CompletionStage;importjava.util.stream.Collectors;importstaticcom.liang.kafka.auth.constants.Constants.*;/**
  2. * kafka acl 自定义鉴权
  3. * 配置方法:在server.properties添加如下配置:
  4. * super.users 超级用户,多个用;隔开
  5. * authorizer.class.name=com.liang.kafka.auth.handler.MyAclAuthorizer
  6. * liang
  7. */publicclassMyAclAuthorizerimplementsAuthorizer{privatestaticfinalLogger logger =LoggerFactory.getLogger(MyAclAuthorizer.class);/**
  8. * 数据源
  9. */privateDruidDataSource dataSource =null;privatestaticfinalStringSUPER_USERS_PROP="super.users";/**
  10. * 超级管理员
  11. */privateSet<String> superUserSet;/**
  12. * 是否开启数据库acl验证
  13. */privateboolean enableDbAcl;@OverridepublicMap<Endpoint,?extendsCompletionStage<Void>>start(AuthorizerServerInfo authorizerServerInfo){//logger.info("------------------start");returnnewHashMap<>();}/**
  14. * 实现你的访问控制逻辑
  15. */@OverridepublicList<AuthorizationResult>authorize(AuthorizableRequestContext authorizableRequestContext,List<Action> list){return list.stream().map(action ->authorizeAction(authorizableRequestContext, action)).collect(Collectors.toList());}/**
  16. * 访问控制逻辑处理
  17. */privateAuthorizationResultauthorizeAction(AuthorizableRequestContext authorizableRequestContext,Action action){ResourcePattern resource = action.resourcePattern();if(resource.patternType()!=PatternType.LITERAL){thrownewIllegalArgumentException("Only literal resources are supported. Got: "+ resource.patternType());}//是否开启数据库acl验证if(!enableDbAcl){returnAuthorizationResult.ALLOWED;}String principal = authorizableRequestContext.principal().getName();AclOperation operation = action.operation();//logger.info("------resource type:{}---name:{}----operation:{}------用户名principal:{}", resource.resourceType(), resource.name(), operation.name(), principal);//1 超级用户直接通过if(superUserSet.contains(principal)){//logger.info("-------------------超级用户直接通过");returnAuthorizationResult.ALLOWED;}//2 资源类型为 Cluster 直接不通过if(resource.resourceType().equals(ResourceType.CLUSTER)){
  18. logger.error("-------------------资源类型为Cluster直接不通过");returnAuthorizationResult.DENIED;}//3 资源类型为 TransactionalId、DelegationToken 直接通过if(resource.resourceType().equals(ResourceType.TRANSACTIONAL_ID)|| resource.resourceType().equals(ResourceType.DELEGATION_TOKEN)){//logger.info("-------------------资源类型为 TransactionalId、DelegationToken 直接通过");returnAuthorizationResult.ALLOWED;}String username = principal;//4 资源类型为 group 只能用默认组消费if(resource.resourceType().equals(ResourceType.GROUP)){if(isGroup(resource.name(), username)){returnAuthorizationResult.ALLOWED;}
  19. logger.error("------------------资源类型为 group:{} 只能用默认分组消费,直接不通过", resource.name());returnAuthorizationResult.DENIED;}//5 查询数据库权限配置表信息,找到则通过,否则不通过if(isAcls(resource.name(), username)){returnAuthorizationResult.ALLOWED;}returnAuthorizationResult.DENIED;}/**
  20. * 判断是否为 默认分组: default_group
  21. */privatebooleanisGroup(String resourceName,String username){String defaultGroup = username +KAFKA_GROUP_SPLIT+"default_group";if(resourceName.equals(defaultGroup)){returntrue;}returnfalse;}/**
  22. * 查询数据库,判断是否有权限
  23. */privateBooleanisAcls(String resourceName,String username){List<String> topics =LocalCache.getCache(username);if(CollUtil.isEmpty(topics)){//从数据库查询
  24. topics =queryDb(username);if(CollUtil.isEmpty(topics)){returnBoolean.FALSE;}LocalCache.addCache(username, topics);}Boolean checkBool =checkTopic(resourceName, topics, username);return checkBool;}/**
  25. * 检查是否有topic权限, topic:username&topic
  26. */privateBooleancheckTopic(String resourceName,List<String> topics,String username){for(String topic : topics){if(topic ==null|| topic.length()==0){continue;}String tmp = username +KAFKA_TOPIC_SPLIT+ topic;if(tmp.equals(resourceName)){returnBoolean.TRUE;}}returnBoolean.FALSE;}/**
  27. * 查询数据库
  28. */privateList<String>queryDb(String username){List<String> dbList =newArrayList<>();String userQuery ="select t.topic\n"+" from topic t\n"+" left join mq_info i on t.mq_id = i.mq_id\n"+" where i.default_instance = 1 and t.del_status = 0 and t.username = ?";Connection conn =null;try{
  29. conn = dataSource.getConnection();PreparedStatement statement = conn.prepareStatement(userQuery);
  30. statement.setString(1, tenantId);ResultSet resultSet = statement.executeQuery();while(resultSet.next()){
  31. dbList.add(resultSet.getString("topic"));}}catch(Exception e){
  32. logger.error("-------------------数据库查询topic异常:{}", e);thrownewRuntimeException(e);}finally{if(conn !=null){try{
  33. conn.close();}catch(SQLException e){thrownewRuntimeException(e);}}}return dbList;}/**
  34. * 创建权限
  35. */@OverridepublicList<?extendsCompletionStage<AclCreateResult>>createAcls(AuthorizableRequestContext authorizableRequestContext,List<AclBinding> list){
  36. logger.error("------------------createAcls----没有创建权限操作");thrownewUnsupportedOperationException();}/**
  37. * 删除权限
  38. */@OverridepublicList<?extendsCompletionStage<AclDeleteResult>>deleteAcls(AuthorizableRequestContext authorizableRequestContext,List<AclBindingFilter> list){
  39. logger.error("------------------deleteAcls----没有删除权限操作");thrownewUnsupportedOperationException();}@OverridepublicIterable<AclBinding>acls(AclBindingFilter aclBindingFilter){//logger.info("------------------acls-----获取符合查询条件的Acl操作");ArrayList aclBindings =newArrayList();return aclBindings;}@Overridepublicvoidclose()throwsIOException{if(dataSource !=null){
  40. dataSource.close();}}@Overridepublicvoidconfigure(Map<String,?> map){String superUsers =(String) map.get(SUPER_USERS_PROP);//logger.info("------------------superUsers:{}", superUsers);if(superUsers ==null|| superUsers.isEmpty()){
  41. superUserSet =newHashSet<>();}else{
  42. superUserSet =Arrays.stream(superUsers.split(";")).map(String::trim).collect(Collectors.toSet());}Object endbAclObject = map.get(ENABLE_DB_ACL);if(Objects.isNull(endbAclObject)){
  43. logger.error("------------------缺少开关配置 enable_db_acl!");
  44. enableDbAcl =Boolean.FALSE;return;}
  45. enableDbAcl =TRUE.equalsIgnoreCase(endbAclObject.toString());if(!enableDbAcl){return;}
  46. dataSource =DataSourceUtil.getIotInstance(map);}}

编译打包运行

编译打成jar包之后,需要放到libs上当,D:\kafka_2.12-3.5.0\libs\xxx。
注意:还有代码中使用了第三方相关依赖包也需要一起放入。
在这里插入图片描述

重启kafka后生效,观察日志,可以看到用户连接后,发送和订阅就会去查询数据库,查询到用户没有权限时,会提示报错如下。

在这里插入图片描述

标签: kafka 分布式 mq

本文转载自: https://blog.csdn.net/yinjl123456/article/details/134516161
版权归原作者 beyond阿亮 所有, 如有侵权,请联系我们删除。

“kafka权限认证 topic权限认证 权限动态认证-亲测成功”的评论:

还没有评论