activemq安全认证

 JAAS Authentication Plugin依赖标准的JAAS机制来实现认证。
 通常情况下,你需要通过设置java.security.auth.login.config系统属性来 配置login modules的配置文件。如果没有指定这个系统属性,那么JAAS Authentication Plugin会缺省使用
 login.config作为文件名
 6.1认证:
 在activemq中的安全概念都是由plug-ins实现,用户可以通过配置activemq xml的plugin元素配置文件,activemq利用两个plug-ins来认证用户
 1.simple authentication plug-in:直接在xml或者property中配置处理隐私
 2jaas  authentication plug-in  :实现了jaas api 并且提供了更强更多的认证解决方案
 
 6.1.1配置简单的认证plug-in
最简单的方法认证broker就是通过直接把认证凭据放在broker'的xml配置文件中,activemq提供了一些简单的认证plug-in

<broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" dataDirectory="${activemq.base}/data">节点下添加以下节点
      <plugins>
        <simpleAuthenticationPlugin>
         <users>
          <authenticationUser username="admin" password="password" groups="admin,publishers,consumers"/>
          <authenticationUser username="publisher" password="password" groups="publishers,consumers"/>
          <authenticationUser username="consumer password="password" groups="consumers"/>
          <authenticationUser username="guest" password="password" groups="guests"/>
         </users>
        </simpleAuthenticationPlugin>
      </plugins>
    通过使用这个简单的片段4个用户就能够简单的接入activemq,显然的,为了达到认证的目的,每个user都有name和password,此外the group可以通过逗号把group分隔成用户属于的组,

package com.activemq.secure;

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;

public class Publisher {
    ActiveMQConnectionFactory connectionFactory =null;
    private String user="publisher";
    private String password="password";
    private String url;
    Session session = null;
    Connection connection=null;
     MessageProducer producer =null;
    public Publisher() throws Exception {
         connectionFactory = new ActiveMQConnectionFactory(url);
         connection = connectionFactory.createConnection(user, password);
         connection.start();
         session=connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
          producer = session.createProducer(null);
    }

}
最好利用简单的认证plugin通过ssl传输
对于那些跟安全的安装以及需要整合更安全的的环境
6.1.2配置jaasplug-in
JAAS提供了认证插件, 那就意味着activemq能够利用相同的认证api而不管用户无论使用的认证凭据(文本文档,关系型数据库,ldap等等),他们的全部都要实现javax.security.auth.spi.LoginModule接口
并且改变activemq配置,activemq提供了一个解决方案(通过property,ssl证书和LDAP来实现一些模块的认证)
1:创建一个文件叫做login.config(配置JAAS user 和group)配置PropertiesLoginModule确保activemq能够使用它
activemq-domain{
org.apache.activemq,jaas.PropertiesLoginModule required
debug=true
org.apache.activemq,jaas.properties.user="users.properties"
org.apache.activemq,jaas.properties.group="groups.properties"
}

2.users.properties

admin=password
publisher=password
consumer=password
guest=password

3.groups.properties

admins=admin
publishers=admin,publisher
consumers=admin,publisher,consumer
guest=guest

4.当这上面三个文件创建以后就在xml里面配置
...
<plugins>
<jaasAuthenticationPlugin configuration="activemq-domain" />
</plugins>
...
6.2认证
active提供了两种级别的认证
1.operate-level运行级别的认证
2.message-level消息级别的认证

6.2.destination level认证
3种user-level opeartion
1.read 2.write 3.admin
    <plugins>
    <jaasAuthenticationPlugin configuration="activemq-domain" />
        <authenticationPlugin>
         <map>
            <authenticationMap>
                <authenticationEntries>
                    <authenticationEntry topic=">" read="admins" write="admins" admin="admins" />
                    <authenticationEntry topic="STOCKS.>" read="consumers" write="publishers" admin="publishers" />
                    <authenticationEntry topic="STOCKS.ORCL" read="guests"  />
                    <authenticationEntry topic="ActiveMQ.Advisory" read="admins,publishers,consumers,guests" write="admins,publishers,consumers,guests" admin="admins,publishers,consumers,guests" />
                </authenticationEntries>
            </authenticationMap>
         </map>
        </authenticationPlugin>
      </plugins>
admins里面的所有user有所有权限到topics
消费者能够消费,生产者能够生产到目的地的stocks 路径下
guests账户只能够消费stocks.orcl topic                              
6.2.2message-level认证《每条消息通过broker的都会被执行》
我们实现了简单的认证plugin允许简单的运行在同一个host消费message,
1.我们需要创建一个org.apache.activemq.security.MessageAuthorizationPolicy
package com.activemq.secure;

import org.apache.activemq.broker.ConnectionContext;
import org.apache.activemq.command.Message;
import org.apache.activemq.security.MessageAuthorizationPolicy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class AuthorizationPolicy implements MessageAuthorizationPolicy {
private static final Log LOG=LogFactory.getLog(AuthorizationPolicy.class);
    @Override
    public boolean isAllowedToConsume(ConnectionContext context, Message message) {
        LOG.info(context.getConnection().getRemoteAddress());
        String remoteAddress=context.getConnection().getRemoteAddress();
        if(remoteAddress.startsWith("/127.0.0.1")){
            LOG.info("Permission to consume granted");
            return true;
        }else{
            LOG.info("Permission to consume dennied");
            return false;
        }
        
    }

}
2.编译这个类并且打包为activemq-in-action-exaples.jar并且考备到activemq的lib包下
3.在xml里配置AuthorizationPolicy
<messageAuthorizationPolicy>
<bean  class="com.activemq.secure.AuthorizationPolicy"
      xmlns="http://www.springframework.org/schema/beans"
/>
</messageAuthorizationPolicy>
4启动activemq并且
6.3构建一个客户安全插件    
brokerFilter拦截了许多可能的broker-level operation , broker能够加入生产者和消费者,提交事务,添加删除connector给broker ,客户的定制化能够通过继承
  brokerFilter 并且重写来实现
1.实现一个JAAS login module
2.实现一个customer plugin  来处理安全
为了用限制ip的方式来限制connectivity我们以下面的Ipauthenticationbroker为列,采取重写brokerfilter.addcoonction方法
package com.activemq.secure;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.activemq.broker.Broker;
import org.apache.activemq.broker.BrokerFilter;
import org.apache.activemq.broker.ConnectionContext;
import org.apache.activemq.command.ConnectionInfo;

public class IPAuthorizationBroker extends BrokerFilter {
    List<String > allowedIPaddresses;
    Pattern pattern=Pattern.compile("^/([0-9\\.]*):(.*)");

    public IPAuthorizationBroker(Broker next ,List<String> allowedIPaddresses ) {
        super(next);
        this.allowedIPaddresses=allowedIPaddresses;
    }
    
 public void addConnection(ConnectionContext context,ConnectionInfo info) throws Exception{
     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("CONECTING FROM IP ADDRESS"+ip +"is not allowed");
            
         }
        
     }else{
         throw new SecurityException("in valid remote address"+remoteAddress);
     }
    
     super.addConnection(context, info);
 }
}  
6.5配置安装plugin
package com.activemq.secure;

import java.util.List;

import org.apache.activemq.broker.Broker;
import org.apache.activemq.broker.BrokerPlugin;

public class IPAuthorizationPlugin implements BrokerPlugin {
List<String>allowedIPAddress;
    @Override
    public Broker installPlugin(Broker broker) throws Exception {
        return new IPAuthorizationBroker(broker,allowedIPAddress);
    }
    public List<String> getAllowedIPAddress() {
        return allowedIPAddress;
    }
    public void setAllowedIPAddress(List<String> allowedIPAddress) {
        this.allowedIPAddress = allowedIPAddress;
    }

}
6.3.2配置plugin
<broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" dataDirectory="${activemq.base}/data">节点下添加以下节点
      <plugins>
        <bean xmlns="http://www.springframework.org/schema/beans"
            id="ipAuthorizationPlugin" class="com.activemq.secure.IPAuthorizationPlugin">
                <property name="allowedIPaddresses">
                    <list>
                        <value>127.0.0.1</value>
                    </list>
                </property>
        </bean>
      </plugins>
      <transportConnectors>
        <transportConnector name=""openwire uri="tcp://localhost:61616"/>
      <transportConnectors>
6.3.3打包为activemq-in-action-exaples.jar放入lib下运行
6.4配置安全证书
keytool -genkey -alias producer -keyalg RSA -keystore myproducer.ks
keytool -genkey -alias consumer -keyalg RSA -keystore myconsumer.ks
6.4.2 create a truststore
keytool -export -alias producer -keystore myproducer.ks -file producer_cert
keytool -export -alias consumer -keystore myconsumer.ks -file consumer_cert
keytool -import -alias producer -keystore mybroker.ts -file producer_cert
keytool -import -alias consumer -keystore mybroker.ts -file consumer_cert
copy mybroker.ts 到conf文件夹下
6.4.3配置broker
<broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" dataDirectory="${activemq.base}/data">节点下添加以下节点
      <plugins>
      <jaasCertificatedAuthenticationPlugin configuration="activemq-certificate">
        <AuthorizationPlugin>
            <map>
            <AuthorizationMap>
                <AuthorizationEntries>
                    <authenticationEntry topic=">" read="admins" write="admins" admin="admins" />
                    <authenticationEntry topic="STOCKS.>" read="consumers" write="publishers" admin="publishers" />
                    <authenticationEntry topic="STOCKS.ORCL" read="guests"  />
                    <authenticationEntry topic="ActiveMQ.Advisory" read="admins,publishers,consumers,guests" write="admins,publishers,consumers,guests" admin="admins,publishers,consumers,guests" />
                </AuthorizationEntries>
            </AuthorizationMap>
            </map>
        </AuthorizationPlugin>
        
      </plugins>
        <sslContext>
        <sslContext keyStore="file:${activemq.base}/conf/mybroker.ks"
        keyStorePASSWORD="test123"
        trustStore="file:${activemq.base}/conf/mybroker.ts"
        trustStorePassword="test123"/>
        </sslContext>
        <transportConnectors>  
                <transportConnector name="openwire" uri="tcp://localhost:61620"/>  
                <transportConnector name="ssl" uri="ssl://localhost:61617?needClientAuth=true"/>
        </transportConnectors>  
</broker>
6.4.4认证
在login.config里面配置
activemq-certificate{
org.apache.activemq.jaas.TextFileCertificateLoginModule
required debug=true
org.apache.activemq.jaas.TextFiledn.user="users.properties"
org.apache.activemq.jaas.TextFiledn.group="groups.properties"
}
users.properties
admin=password
publisher=password
consumer=password
guest=password
sslconsumer=CN=consumer,OU=Chapter 6,O=ActiveMQ in Action,L=belgrade,ST=Unknown, C=RS
sslpublisher=CN=producer,OU=Chapter 6,O=ActiveMQ in Action,L=belgrade,ST=Unknown, C=RS

groups.properties
admins=admin
publishers=admin,publisher,sslpublisher
consumers=admin,publisher,consumer,sslconsumer
guests=guest



你可能感兴趣的:(activemq安全认证)