Spring Boot中禁用ActiveMQ的SSL证书验证方法问询
解决Spring Boot中ActiveMQ自签名SSL证书验证禁用问题
在本地测试场景下,要绕过ActiveMQ的自签名SSL证书验证及主机名不匹配问题,无需手动注入会话,只需自定义ActiveMQ连接工厂,替换Spring Boot的默认配置即可,具体步骤如下:
1. 创建信任所有证书的SSLContext工具类
实现一个信任任意证书的X509TrustManager,并生成对应的SSLContext:
import javax.net.ssl.*; import java.security.cert.X509Certificate; public class TrustAllSslContext { public static SSLContext create() throws Exception { X509TrustManager trustManager = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) {} @Override public void checkServerTrusted(X509Certificate[] chain, String authType) {} @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[]{trustManager}, new java.security.SecureRandom()); return sslContext; } }
2. 自定义ActiveMQ连接工厂配置类
编写Spring配置类,覆盖默认的ConnectionFactory,注入自定义SSLContext并禁用主机名验证:
import org.apache.activemq.ActiveMQConnectionFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jms.annotation.EnableJms; import javax.net.ssl.SSLContext; @Configuration @EnableJms public class ActiveMQConfig { @Value("${spring.activemq.broker-url}") private String brokerUrl; @Value("${spring.activemq.user}") private String username; @Value("${spring.activemq.password}") private String password; @Bean public ActiveMQConnectionFactory activeMQConnectionFactory() throws Exception { ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(username, password, brokerUrl); // 加载信任所有证书的SSLContext SSLContext sslContext = TrustAllSslContext.create(); factory.setSslContext(sslContext); // 禁用主机名匹配验证 factory.setVerifyHostName(false); return factory; } }
3. 确认配置文件中的ActiveMQ参数
确保你的application.properties或application.yml配置了SSL协议的Broker地址:
spring.activemq.broker-url=tls://localhost:61617 spring.activemq.user=admin spring.activemq.password=admin
注意:该配置仅适用于本地测试场景,严禁在生产环境使用,会完全忽略SSL证书的安全性校验,带来极大的安全风险。
内容的提问来源于stack exchange,提问作者MasterMind
相关产品推荐
相关产品推荐

