ActiveMQ的自定义安全插件(十)

来源:互联网 发布:如何购买已备案的域名 编辑:程序博客网 时间:2024/06/07 20:02

ActivityMQ的自定义安全插件


上一节提到了ActivityMQ的两种安全插件

  • Simple Authentication(简单的身份验证)

  • JAAS authentication(JAAS身份验证)

最先考虑的应该是实现JAAS身份认证,如果一些需求JAAS不能满足的话,就要采取自定义安全插件的方法


1.首先写一个自定义的Broker,继承BrokerFilter,实现addConnection方法,实现的功能是只允许特定的ip访问Broker

public class IPAuthenticationBroker extends BrokerFilter {List<String> allowedIPAddresses;Pattern pattern = Pattern.compile("^/([0-9\\.]*):(.*)"); public IPAuthenticationBroker(Broker next, List<String>      allowedIPAddresses) {  super(next);  this.allowedIPAddresses = allowedIPAddresses;}public void addConnection(ConnectionContext      context, ConnectionInfo info) throws Exception {Filter connections based on IP address  String remoteAddress = context.getConnection().getRemoteAddress(); Matcher matcher = pattern.matcher(remoteAddress);    if (matcher.matches()) {      String ip = matcher.group(1);      if (!allowedIPAddresses.contains(ip)) {        throw new SecurityException("Connecting from IP address "          + ip + " is not allowed" );}} else {      throw new SecurityException("Invalid remote address "          + remoteAddress);}    super.addConnection(context, info);  }}

2.然后写一个自定义插件类,实现BrokerPlugin的installPlugin方法

注意:这个方法返回一个BrokerFilter的实现类,可以理解这里有很多个Filter,每次Broker经过一个Filter返回他自己,在经过下一个Filter再返回他自己,这点与javaee的controller是一样的;还有一定要有构造函数参数的getter和setter方法,和spring注入一致

public class IPAuthenticationPlugin implements BrokerPlugin { List<String> allowedIPAddresses;public Broker installPlugin(Broker broker) throws Exception {return new IPAuthenticationBroker(broker, allowedIPAddresses); }  public List<String> getAllowedIPAddresses() {    return allowedIPAddresses;}Create instance of custom class  public void setAllowedIPAddresses(List<String> allowedIPAddresses) { this.allowedIPAddresses = allowedIPAddresses;} }

3.接着我们只需要把这个plugin添加到activitymq.xml中就可以了

<broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" dataDirectory="${activemq.base}/data">    <plugins>    <bean xmlns="http://www.springframework.org/schema/beans"id="ipAuthenticationPlugin" class="org.apache.activemq.book.ch6.IPAuthenticationPlugin">                   <property name="allowedIPAddresses">                       <list>                           <value>127.0.0.1</value>                       </list>          </bean>    </plugins>    </property></broker>

当然,这个maven项目也要mvn clean install,打包到maven仓库里面,然后把ipAuthenticationPlugin的类的路径改掉就能正常运行了

原创粉丝点击