嵌入式ActiveMQ SimpleAuthenticationPlugin失效:队列允许任意连接
解决Spring Boot嵌入式ActiveMQ的SimpleAuthenticationPlugin不生效问题
问题根源
Spring Boot的嵌入式ActiveMQ不会自动加载独立版ActiveMQ的/conf目录配置,也不会默认识别resources文件夹中的插件XML配置,必须通过自定义配置类手动注册认证插件,这就是你当前任意账号都能连接的原因。
解决方案:自定义Broker配置类
创建Spring配置类,通过ActiveMQBrokerFactoryCustomizer手动注入SimpleAuthenticationPlugin,确保嵌入式Broker加载认证规则:
import org.apache.activemq.broker.BrokerPlugin; import org.apache.activemq.security.SimpleAuthenticationPlugin; import org.apache.activemq.security.AuthenticationUser; import org.springframework.boot.autoconfigure.jms.activemq.ActiveMQBrokerFactoryCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Collections; @Configuration public class ActiveMQSecurityConfig { @Bean public ActiveMQBrokerFactoryCustomizer brokerFactoryCustomizer() { return brokerFactoryBean -> { // 初始化认证插件,禁用匿名访问 SimpleAuthenticationPlugin authPlugin = new SimpleAuthenticationPlugin(); authPlugin.setAnonymousAccessAllowed(false); // 添加授权用户(可添加多个) AuthenticationUser authorizedUser = new AuthenticationUser( "myUser", "myPassword", "users,admins" ); authPlugin.setUsers(Collections.singletonList(authorizedUser)); // 将插件绑定到Broker brokerFactoryBean.setPlugins(new BrokerPlugin[]{authPlugin}); }; } }
客户端连接配置
确保你的JMS客户端(生产者/消费者)连接时携带正确的用户名密码,在application.properties中配置:
# 嵌入式Broker地址 spring.activemq.broker-url=tcp://localhost:61616 # 连接用户名 spring.activemq.user=myUser # 连接密码 spring.activemq.password=myPassword
验证生效
用错误的用户名密码尝试连接Broker,此时应该会收到认证失败的异常,说明插件已生效,不再允许任意账号连接。
内容的提问来源于stack exchange,提问作者It Grunt
相关产品推荐
相关产品推荐

