基于SOAP的Web安全调用机制-----Axis2+Rampart(WSS4J)实现UsernameToken认证方式的WS-Security【未试验】

文章来源:http://blog.csdn.net/wwwgeyang777/article/details/19928631


最近一直研究SOAP消息的安全通信方式,没在网上搜到啥靠谱的,就一步一步摸索,终于成功了,把过程整理出来,供大家参考。

 

 

废话不多说,关于怎么用Axis2发布Web Service,WS-Security是啥,什么是Rampart、和WSS4J又是什么关系,SOAP消息等等的问题不是本文的重点,这里推荐一篇文章,是用Axis2+Rampart实现证书认证方式的WS-Security,写的比较好,对相关的概念也有部分介绍,必须得赞一个,一系列的文章也都写的非常好,值得细细品读。

地址:http://blog.csdn.net/lifetragedy/article/details/7844589

 

 

1、 服务端

最终建好的工程截图如下:

 

a)      建立Axis2的工程

b)     添加相关的Jar包,Axis2、Rampart的jar包都需要有,由于本项目中还用到了数据库,所以也添加了jdbc的jar包。

c)      之后在WEB-INF/modules目录下添加rampart模块,将rampart-1.6.2.mar和rahas-1.6.2.mar两个文件直接拷过来即可。

d)     之后就是在配置文件services.xml中添加rampart的配置,内容如下:

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. <module ref="rampart" />  
  2. <!--   
  3. <parameter name="OutflowSecurity">  
  4.     <action>  
  5.         <items>UsernameToken</items>  
  6.         <user>administrator</user>  
  7.         <passwordCallbackClass>com.rampart.client.ClientAuthHandler  
  8.         </passwordCallbackClass>  
  9.     </action>  
  10. </parameter>  
  11.  -->  
  12. <parameter name="InflowSecurity">  
  13.     <action>  
  14.         <items>UsernameToken</items>  
  15.         <passwordCallbackClass>com.rampart.WsServiceAuthHandler</passwordCallbackClass>  
  16.     </action>  
  17. </parameter>  

 

因为服务端只是对访问请求进行验证,所以对OutflowSecurity参数不做设置。InflowSecurity参数项配置里面的passwordCallbackClass需要配置自己写的回调函数的类名,代码如下:

 

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.rampart;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import javax.security.auth.callback.Callback;  
  6. import javax.security.auth.callback.CallbackHandler;  
  7. import javax.security.auth.callback.UnsupportedCallbackException;  
  8.   
  9. import org.apache.log4j.Logger;  
  10. import org.apache.ws.security.WSPasswordCallback;  
  11.   
  12. public class WsServiceAuthHandler implements CallbackHandler  
  13. {  
  14.     private final static String USERNAME = "administrator";  
  15.     private final static String PASSWORD = "123456";  
  16.     private Logger log = Logger.getLogger(WsServiceAuthHandler.class);  
  17.   
  18.     /** 
  19.      * 〈一句话功能简述〉 〈功能详细描述〉 
  20.      *  
  21.      * @see javax.security.auth.callback.CallbackHandler#handle(javax.security.auth.callback.Callback[]) 
  22.      * @param callbacks 
  23.      * @throws IOException 
  24.      * @throws UnsupportedCallbackException 
  25.      */  
  26.     @Override  
  27.     public void handle(Callback[] callbacks) throws IOException,  
  28.         UnsupportedCallbackException  
  29.     {  
  30.         WSPasswordCallback pCallback = (WSPasswordCallback) callbacks[0];  
  31.         // 标识符  
  32.         String id = pCallback.getIdentifier();  
  33.         // 此处获取到的password为null,但是并不代表服务端没有拿到该属性。  
  34.         // 这是因为客户端提交过来的密码在SOAP 消息中已经被加密为MD5  
  35.         // 的字符串,如果我们要在回调方法中作比较,那么第一步要做的就是把服务端准备好的密码加密为MD5 字符串,由于MD5  
  36.         // 算法参数不同结果也会有差别,另外,这样的工作由框架替我们完成不是更简单吗?  
  37.         String password = pCallback.getPassword();  
  38.         System.out.println("接收到WebService请求,userName[" + id + "],password["  
  39.             + password + "]......");  
  40.   
  41.         if (null == USERNAME)  
  42.         {  
  43.             System.out.println("验证用户失败,原因:您没有权限访问,用户名为空!");  
  44.             throw new UnsupportedCallbackException(pCallback, "您没有权限访问,用户名为空!");  
  45.         }  
  46.         else if (!USERNAME.equals(id))  
  47.         {  
  48.             System.out.println("验证用户失败,原因:您没有权限访问,用户名错误!");  
  49.             throw new UnsupportedCallbackException(pCallback, "您没有权限访问,用户名错误!");  
  50.         }  
  51.         else  
  52.         {  
  53.             /** 
  54.              * 此处应该这样做:  
  55.              * 1. 查询数据库,得到数据库中该用户名对应密码  
  56.              * 2. 设置密码,wss4j会自动将你设置的密码与客户端传递的密码进行匹配  
  57.              * 3. 如果相同,则放行,否则返回权限不足信息 
  58.              */  
  59.             pCallback.setPassword(PASSWORD);  
  60.             /* 
  61.              * if (!PASSWORD.equals(password)) { 
  62.              * System.out.println("验证用户失败,原因:您没有权限访问,密码错误!"); throw new 
  63.              * UnsupportedCallbackException(pCallback, "您没有权限访问,密码错误!"); } 
  64.              */  
  65.         }  
  66.   
  67.         pCallback.setIdentifier("service");  
  68.     }  
  69.   
  70. }  

 

具体什么什么的看注释就行了,可以说是综合了网上能找的所有资料里面感觉有道理的说明的总和了。

 

e)      再然后就发布服务就行了。

 

 

2、 客户端

客户端的配置相对来说就比较麻烦了,一步一步来吧。

客户端只要建立普通的Java工程就行了,最终工程截图如下:

 

a)      新建Java工程

b)     同样添加相关的Jar包,Axis2、Rampart的jar包都需要有。

c)      这里就在src下面新建个repository的目录,将axis2.xml文件从Axis2的conf目录下拷过来,然后再将modules目录全部拷过来。

d)     之后是新建类,编写调用的客户端代码,其中的关键代码如下:

 

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.client;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.Iterator;  
  5. import java.util.List;  
  6.   
  7. import org.apache.axiom.om.OMAbstractFactory;  
  8. import org.apache.axiom.om.OMElement;  
  9. import org.apache.axiom.om.OMFactory;  
  10. import org.apache.axiom.om.OMNamespace;  
  11. import org.apache.axiom.om.OMNode;  
  12. import org.apache.axis2.addressing.EndpointReference;  
  13. import org.apache.axis2.client.Options;  
  14. import org.apache.axis2.client.ServiceClient;  
  15. import org.apache.axis2.context.ConfigurationContext;  
  16. import org.apache.axis2.context.ConfigurationContextFactory;  
  17. import org.apache.axis2.databinding.utils.BeanUtil;  
  18. import org.apache.axis2.engine.DefaultObjectSupplier;  
  19.   
  20. import com.bean.PeopleStatisticsInfo;  
  21.   
  22. public class DocumentClient  
  23. {  
  24.   
  25.     private static EndpointReference targetEPR = new EndpointReference(  
  26.         "http://localhost:1235/WSS4JServer/services/ZhiliDspServices");  
  27.   
  28.     private String getAxis2ConfPath()  
  29.     {  
  30.         StringBuilder confPath = new StringBuilder();  
  31.         confPath.append(this.getClass().getResource("/").getPath());  
  32.         confPath.append("repository");  
  33.         return confPath.toString();  
  34.     }  
  35.   
  36.     private String getAxis2ConfFilePath()  
  37.     {  
  38.         String confFilePath = "";  
  39.         confFilePath = getAxis2ConfPath() + "/axis2.xml";  
  40.         return confFilePath;  
  41.   
  42.     }  
  43.   
  44.     public void invokeRampartService()  
  45.     {  
  46.         System.out  
  47.             .println("****** Invoking function: invokeRampartService ******");  
  48.   
  49.         Options options = new Options();  
  50.         options.setTo(targetEPR);  
  51.         options.setAction("urn:getAllPeopleStatistics");  
  52.   
  53.         ServiceClient sender = null;  
  54.   
  55.         try  
  56.         {  
  57.             String confPath = getAxis2ConfPath();  
  58.             String confFilePath = getAxis2ConfFilePath();  
  59.             System.out.println("confPath ====== " + confPath);  
  60.             System.out.println("confFilePath ==== " + confFilePath);  
  61.   
  62.             ConfigurationContext configContext = ConfigurationContextFactory  
  63.                 .createConfigurationContextFromFileSystem(confPath,  
  64.                     confFilePath);  
  65.             sender = new ServiceClient(configContext, null);  
  66.             sender.setOptions(options);  
  67.   
  68.             OMFactory fac = OMAbstractFactory.getOMFactory();  
  69.             OMNamespace omNs = fac.createOMNamespace(  
  70.                 "http://ws.apache.org/axis2""");  
  71.             OMElement callMethod = fac.createOMElement(  
  72.                 "getAllPeopleStatistics", omNs);  
  73.   
  74.             OMElement response = sender.sendReceive(callMethod);  
  75.             System.out.println("response ====>" + response);  
  76.             System.out.println(response.getFirstElement().getText());  
  77.     
  78.         }  
  79.         catch (Exception e)  
  80.         {  
  81.             e.printStackTrace();  
  82.         }  
  83.         finally  
  84.         {  
  85.             if (sender != null)  
  86.                 sender.disengageModule("addressing");  
  87.             try  
  88.             {  
  89.                 sender.cleanup();  
  90.             }  
  91.             catch (Exception e)  
  92.             {  
  93.             }  
  94.         }  
  95.     }  
  96.   
  97.     public static void main(String[] args)  
  98.     {  
  99.         DocumentClient documentClient = new DocumentClient();  
  100.         documentClient.invokeRampartService();  
  101.     }  
  102. }  

 

e)      这样就能调用了吗?还没有完,还要配置?对,就是配置,不过这里配置的是拷过来axis2.xml文件,添加内容如下:

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. <module ref="rampart" />  
  2.      
  3.    <parameter name="OutflowSecurity">  
  4.        <action>  
  5.            <items>UsernameToken</items>  
  6.            <user>administrator</user>  
  7.            <passwordCallbackClass>com.rampart.client.ClientAuthHandler  
  8.            </passwordCallbackClass>  
  9.        </action>  
  10.    </parameter>  
  11.    <!--   
  12.    <parameter name="InflowSecurity">  
  13.        <action>  
  14.            <items>UsernameToken</items>  
  15.            <passwordCallbackClass>com.rampart.client.ServiceAuthHandler  
  16.            </passwordCallbackClass>  
  17.        </action>  
  18.    </parameter>  
  19.     -->  



因为是调用的代码,只需要配置OutflowSecurity就行了,不需要的InflowSecurity给注释掉。OutflowSecurity中设置的passwordCallbackClass多对应的回调函数的代码也给贴出来了,如下:

[java]  view plain copy print ?
  1. package com.rampart.client;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import javax.security.auth.callback.Callback;  
  6. import javax.security.auth.callback.CallbackHandler;  
  7. import javax.security.auth.callback.UnsupportedCallbackException;  
  8.   
  9. import org.apache.log4j.Logger;  
  10. import org.apache.ws.security.WSPasswordCallback;  
  11.   
  12. public class ClientAuthHandler implements CallbackHandler  
  13. {  
  14.     private final static String USERNAME = "administrator";  
  15.     private final static String PASSWORD = "123456";  
  16.     private Logger log = Logger.getLogger(ClientAuthHandler.class);  
  17.   
  18.     /** 
  19.      * 〈一句话功能简述〉 〈功能详细描述〉 
  20.      *  
  21.      * @see javax.security.auth.callback.CallbackHandler#handle(javax.security.auth.callback.Callback[]) 
  22.      * @param callbacks 
  23.      * @throws IOException 
  24.      * @throws UnsupportedCallbackException 
  25.      */  
  26.     @Override  
  27.     public void handle(Callback[] callbacks) throws IOException,  
  28.         UnsupportedCallbackException  
  29.     {  
  30.         System.out.println("客户端 wss4j内容加密并发送到服务端......");  
  31.         for (int i = 0; i < callbacks.length; i++)  
  32.         {  
  33.             WSPasswordCallback pCallback = (WSPasswordCallback) callbacks[i];  
  34.             String id = pCallback.getIdentifier();  
  35.             if (USERNAME.equals(id))  
  36.             {  
  37.                 pCallback.setPassword(PASSWORD);  
  38.             }  
  39.   
  40.             // pCallback.setPassword(PASSWORD);  
  41.             // pCallback.setIdentifier(USERNAME);  
  42.         }  
  43.     }  
  44.   
  45. }  



f)      好了,可以调用了,是不是很兴奋啊!


3、测试

这么多的配置到底是为了什么呢?监听下SOAP请求信息,看到request的信息如下:


<?xml version="1.0" encoding="http://schemas.xmlsoap.org/soap/envelope/" standalone="no"?>

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">  
  2.     <soapenv:Header xmlns:wsa="http://www.w3.org/2005/08/addressing">  
  3.         <wsse:Security  
  4.             xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"  
  5.             xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"  
  6.             soapenv:mustUnderstand="1">  
  7.             <wsse:UsernameToken wsu:Id="UsernameToken-1">  
  8.                 <wsse:Username>administrator</wsse:Username>  
  9.                 <wsse:Password  
  10.                     Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">1Rjr1XAOJQMeRGzxq5uNVRuoux8=</wsse:Password>  
  11.                 <wsse:Nonce  
  12.                     EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">aHlI/3CcTUy4xlGS8caxuQ==</wsse:Nonce>  
  13.                 <wsu:Created>2014-02-25T00:53:15.832Z</wsu:Created>  
  14.             </wsse:UsernameToken>  
  15.         </wsse:Security>  
  16.         <wsa:To>http://localhost:1235/WSS4JServer/services/ZhiliDspServices  
  17.         </wsa:To>  
  18.         <wsa:MessageID>urn:uuid:43409459-de4c-4e92-9a11-d67a42afce31  
  19.         </wsa:MessageID>  
  20.         <wsa:Action>urn:getAllPeopleStatistics</wsa:Action>  
  21.     </soapenv:Header>  
  22.     <soapenv:Body>  
  23.         <getAllPeopleStatistics xmlns="http://ws.apache.org/axis2" />  
  24.     </soapenv:Body>  
  25. </soapenv:Envelope>  

可以看到,这里面把密码给加密了,然后还有一堆乱七八糟看不懂的东西,安全性算是有一定程度的保障吧。


由于代码有很多的涉及业务范围的东西,就不贴出了,有问题的话可以留言或者发消息。

写的有点仓促,很多东西都很浅显,敬请谅解!





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值