一: Web Service security UserNameToken 概念

原理:用户在发送请求的时候,在Soap head中加入自己的用户名以及密码,接受请求的Service通过之前与Client建立的共享密码来验证密码的合法性从而实现鉴别用户的功能。

  1. <wsse:UsernameToken>
  2. <wsse:Username>NNK</wsse:Username>
  3. <wsse:Password Type="...#PasswordDigest">
  4. weYI3nXd8LjMNVksCKFV8t3rgHh3Rw==
  5. </wsse:Password>
  6. <wsse:Nonce>WScqanjCEAC4mQoBE07sAQ==</wsse:Nonce>
  7. <wsu:Created>2003-07-16T01:24:32Z</wsu:Created>
  8. </wsse:UsernameToken>

Password_Digest = Base64 ( SHA-1 ( nonce + created + password ) )
wsse:Nonce和wsu:Created这两个元素的作用:是为了避免重放(Replay)***。

只要对密码做一些处理就可以从中派生出密钥。当然为了安全起见我们希望每次派生出来的密钥都不一样,这样就可以避免多次使用同一密钥而导致密钥被破解。下面就是WS-Security对密钥派生的元素定义:

  1. <wsse:UsernameToken wsse:Id=”…”>
  2. <wsse:Username>…</wsse:Username>
  3. <wsse11:Salt>…</wsse11:Salt>
  4. <wsse11:Iteration>…</wsse11:Iteration>
  5. </wsse:UsernameToken>

其中Salt是导致密钥变化的因子,Iteration是密钥派生时Hash的次数。
密码的派生公式如下:
K1 = SHA1( password + Salt)  K2 = SHA1( K1 )  … Kn = SHA1 ( Kn-1)

二:代码示例

xml文件:

  1. Request xml:
  2. <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://www.webserviceX.NET/">
  3. <soapenv:Header/>
  4. <soapenv:Body>
  5. <web:ConversionRate>
  6. <web:FromCurrency>1</web:FromCurrency>
  7. <web:ToCurrency>2</web:ToCurrency>
  8. </web:ConversionRate>
  9. </soapenv:Body>
  10. </soapenv:Envelope>
  11. Response xml:
  12. <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://www.webserviceX.NET/">
  13. <soapenv:Header/>
  14. <soapenv:Body>
  15. <web:ConversionRateResponse>
  16. <web:ConversionRateResult>88</web:ConversionRateResult>
  17. </web:ConversionRateResponse>
  18. </soapenv:Body>
  19. </soapenv:Envelope>

1 直接使用httpclient调用service

  1. public static String soapSpecialConnection(String url) throws Exception
  2. {
  3. //拼装soap请求报文
  4. StringBuilder sb = new StringBuilder();
  5. StringBuilder soapHeader = new StringBuilder();
  6. soapHeader.append("<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://www.webserviceX.NET/\">");
  7. soapHeader.append("<SOAP-ENV:Header/>");
  8. soapHeader.append("<SOAP-ENV:Body>");
  9. soapHeader.append("<web:ConversionRate>");
  10. soapHeader.append("<web:FromCurrency>123</web:FromCurrency>");
  11. soapHeader.append("<web:ToCurrency>123</web:ToCurrency>");
  12. soapHeader.append("</web:ConversionRate>");
  13. soapHeader.append("</SOAP-ENV:Body>");
  14. soapHeader.append("</SOAP-ENV:Envelope>");
  15. //设置soap请求报文的相关属性
  16. URL u = new URL(url);
  17. HttpURLConnection conn = (HttpURLConnection) u.openConnection();
  18. conn.setDoInput(true);
  19. conn.setDoOutput(true);
  20. conn.setUseCaches(false);
  21. conn.setDefaultUseCaches(false);
  22. conn.setRequestProperty("Host", "localhost:8080");
  23. conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
  24. conn.setRequestProperty("Content-Length", String.valueOf(soapHeader.length()));
  25. conn.setRequestProperty("SOAPAction", "");
  26. conn.setRequestMethod("POST");
  27. //定义输出流
  28. OutputStream output = conn.getOutputStream();
  29. if (null != soapHeader) {
  30. byte[] b = soapHeader.toString().getBytes("utf-8");
  31. //发送soap请求报文
  32. output.write(b, 0, b.length);
  33. }
  34. output.flush();
  35. output.close();
  36. //定义输入流,获取soap响应报文
  37. InputStream input = conn.getInputStream();
  38. int c = -1;
  39. //sb为返回的soap响应报文字符串
  40. while (-1 != (c = input.read())) {
  41. sb.append((char)c);
  42. }
  43. input.close();
  44. return sb.toString();
  45. }

2 使用apache的axis 来调用service

  1. private void callRequest() throws SOAPException {
  2. String    NAMESPACE_URI = "http://www.webserviceX.NET/";
  3. String    PREFIX        = "web";
  4. String url = "http://localhost:28080/MockService";
  5. SOAPConnectionFactory connectionFactory=SOAPConnectionFactory.newInstance();
  6. MessageFactory        messageFactory=MessageFactory.newInstance();
  7. SOAPFactory           soapFactory = SOAPFactory.newInstance();
  8. SOAPMessage message = messageFactory.createMessage();
  9. SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
  10. envelope.addNamespaceDeclaration(PREFIX, NAMESPACE_URI);
  11. Name requestName = soapFactory.createName("ConversionRate", PREFIX, NAMESPACE_URI);
  12. SOAPBodyElement trackRequestElement = message.getSOAPBody().addBodyElement(requestName);
  13. SOAPElement element1, element2;
  14. element1 = trackRequestElement.addChildElement(soapFactory.createName("FromCurrency", PREFIX, NAMESPACE_URI));
  15. element2 = trackRequestElement.addChildElement(soapFactory.createName("ToCurrency", PREFIX, NAMESPACE_URI));
  16. element1.addTextNode("123");
  17. element2.addTextNode("123");
  18. MimeHeaders hd = message.getMimeHeaders();
  19. hd.setHeader("SOAPAction", "");
  20. hd.setHeader("Content-Type", "text/xml; charset=utf-8");
  21. SOAPConnection connection = connectionFactory.createConnection();
  22. SOAPMessage response = connection.call(message, url);
  23. }

3 输出为xml,便于调试

  1. public void wirteToxml(String fileName, SOAPMessage request) throws Exception {
  2. FileWriter fw = new FileWriter(fileName, true); // outputFile为要写入的.xml文件,如result.xml
  3. BufferedWriter bw = new BufferedWriter(fw);
  4. Source source = request.getSOAPPart().getContent();
  5. Transformer transformer = TransformerFactory.newInstance().newTransformer();
  6. ByteArrayOutputStream myOutStr = new ByteArrayOutputStream();
  7. StreamResult res = new StreamResult();
  8. res.setOutputStream(myOutStr);
  9. transformer.transform(source, res);
  10. String temp = myOutStr.toString().trim();
  11. bw.write(temp);
  12. bw.newLine();
  13. bw.flush();
  14. bw.close();
  15. }

4 设置 web service security

  1. protected void buildHeader(SOAPMessage message) throws SOAPException {
  2. String username = "1234";
  3. String password = "1234";
  4. final String SECURITY_PREFIX = "wsse";
  5. SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
  6. SOAPHeader soapHead = message.getSOAPHeader();
  7. SOAPHeaderElement security = soapHead.addHeaderElement(envelope.createName("Security", SECURITY_PREFIX,
  8. "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"));
  9. security.setMustUnderstand(true); // 服务方必须能够识别校验,否则失败
  10. SOAPElement usernameToken = security.addChildElement("UsernameToken", SECURITY_PREFIX);
  11. usernameToken.addNamespaceDeclaration("wsu",
  12. "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
  13. SOAPElement usernameNode = usernameToken.addChildElement("Username", SECURITY_PREFIX);
  14. usernameNode.setValue(username);
  15. SOAPElement passwordNode = usernameToken.addChildElement("Password", SECURITY_PREFIX);
  16. passwordNode.setAttribute("Type",
  17. "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
  18. passwordNode.setValue(password);
  19. }

mustUnderstand:用于标注security header是否必须被service端解析处理

三:测试工具

TCPMon :   http://ws.apache.org/commons/tcpmon/tcpmontutorial.html 可视化发送请求的信息,以及返回结果的信息,便于调试

转载于:https://blog.51cto.com/drizzlewalk/1149515

Web Service security UserNameToken 使用相关推荐

  1. web service security profile的设计

    要获取更多Jerry的原创文章,请关注公众号"汪子熙":

  2. 通向架构师的道路(第十四天)Axis2 Web Service安全之rampart

    2019独角兽企业重金招聘Python工程师标准>>> 一.加密保护我们的web service传输 在上一天的教程中,我们讲了一个简单的基于" security-cons ...

  3. Silverlight访问Web Service报System.Security.SecurityException: 安全性错误的处理

    Silverlight访问Web Service报"System.Security.SecurityException: 安全性错误"的处理 好几次了,执行的好好的Silverli ...

  4. Apache CXF实战之六 创建安全的Web Service

    2019独角兽企业重金招聘Python工程师标准>>> 本文链接:http://blog.csdn.net/kongxx/article/details/7534035 Apache ...

  5. 使用WSE实现Web Service安全

    WSE(Web Services Enhancements)是微软为了使开发者通过.NET创建出更强大,更好用的Web Services而推出功能增强插件.现在最新的版本是WSE2.0(SP2).本文 ...

  6. Java 调用Web service 添加认证头(soapenv:Header)

    前言 有时候调用web service 会出现 Message does not conform to configured policy [ AuthenticationTokenPolicy(S) ...

  7. Web Service 安全性解决方案(SOAP篇)

    拼吾爱程序人生 » 软件编程 » Visual Studio.NET » Web Service » Web Service 安全性解决方案(SOAP篇) Web Service 安全性解决方案(SO ...

  8. 论文阅读 Current Solutions for Web Service Composition

    简单信息 Title Current solutions for Web service composition Journal IEEE Internet Computing Year 2004 A ...

  9. 银光中国网免费Silverlight空间Web Service部署方法

    银光中国网为方便大家学习Silverlight技术,特别推出Silverlight免费空间服务.看到论坛上有不少开发人员询问在部署WCF或者Web Service应用时出现异常,无法部署成功,这里我做 ...

最新文章

  1. 第五课-第三讲05_03_bash脚本编程之二 条件判断
  2. public lt;Tgt; void method,此地泛型的意思
  3. python怎么画简单图片-小白艰难的Python图像的绘制
  4. Set the roller speed
  5. 使用RDLC报表向报表传入参数
  6. gprof + kprof + gprof2dot (性能 与 函数调用图)-
  7. http headers详解
  8. 今天在网上看到一个帖子,怎么样锻炼自己的大脑
  9. Fiori里花瓣的动画效果实现原理
  10. asp.net 报表页面模板_20套大屏模板,教你3分钟制作出酷炫的可视化大屏
  11. 贪心算法之用优先队列(priority_queue)实现哈夫曼编码问题
  12. 线程轮循打印ABC...
  13. webservice studio 参数是DataSet时不支持中文 解决方法
  14. FFmpeg实现多段小视频合成
  15. string与StringBuilder 性能差距到底有多大
  16. 深度优先搜索 - 最短路径
  17. 杭州云栖大会“弹性计算用户实践专场”等你来
  18. 水波纹特效怎么制作?这波水波纹特效拉动满满复古感
  19. 套接字Socket编程
  20. openlayers 6 图层望远镜功能的实现

热门文章

  1. C++(STL):01---pair容器
  2. C:02---scanf、printf
  3. AWS 给负载均衡器配置侦听器并上传IAM证书
  4. 深度学习(02)-- ANN学习
  5. linux中网页播放音乐,Linux_在Linux系统下播放网页中的背景音乐技巧,在Linux中的firefox浏览许多网页 - phpStudy...
  6. 使用国密浏览器和使用Wireshark进行国密抓包
  7. 中医教你5个补肾护发食疗方
  8. 职场:人生从没有最佳时机!一个离职客服人员的领悟
  9. 从创业失败中学到的七条教训
  10. MPEG-4 AVC/H.264 信息