---
title: "webService----wss4j+cxf实现WS-Security(基于UsernameToken)"
author: "mxdxm"
date: "2017-10-23T18:58:23Z"
tags: []
categories: ["非技术"]
slug: "webservice-wss4j-cxf-ws-security-usernametoken"
draft: false
lastmod: "2017-10-23T18:58:23Z"
id: 2397380
url: "https://mxdxm.iteye.com/blog/2397380"
---

分享一下wss4j+cxf基于UsernameToken的安全验证。名词解释：      

      cxf         : apache下的一个开源项目，用于发布webservice。  
      WSS4J  : Web Services Security for Java. 

废话少说，直接上代码。  
    1. 首先，需要导入cxf中的所有jar包，及wss4j中的所有jar包与log4j.jar。  
          (本例中使用的版本是：apache-cxf-2.7.3，wss4j-1.6.9)  
  

  2. 首先建立server 项目，发布一个简单的helloWorldService. 

 

目录结构图：

![](http://dl.iteye.com/upload/attachment/0081/8149/f921e7c8-5744-3c8a-b21a-cf936adf6390.jpg)  
 

   
    webservice接口代码：  
   

Java代码  [![收藏代码](http://q269223.iteye.com/images/icon_star.png)]()

1. package com.wss4j.server;
2. import javax.jws.WebParam;
3. import javax.jws.WebService;
4. @WebService
5. public interface HelloWorld {
6. public String sayHello(@WebParam(name = "name") String name);
7. }

 webservice实现类

 

 

Java代码  [![收藏代码](http://q269223.iteye.com/images/icon_star.png)]()

1. package com.wss4j.server;
2. public class HelloWorldImpl implements HelloWorld {
3. @Override
4. public String sayHello(String name) {
5. return "Hello " + name + " ^\_^ !";
6. }
7. }

 

 

 接下来是服务端拦截器: ServerPasswordCallback.java

 

Java代码  [![收藏代码](http://q269223.iteye.com/images/icon_star.png)]()

01. package com.wss4j.interceptor;
02. import java.io.IOException;
03. import javax.security.auth.callback.Callback;
04. import javax.security.auth.callback.CallbackHandler;
05. import javax.security.auth.callback.UnsupportedCallbackException;
06. import org.apache.ws.security.WSPasswordCallback;
07. import org.slf4j.Logger;
08. public class ServerPasswordCallback implements CallbackHandler {
09. private Logger logger = org.slf4j.LoggerFactory.getLogger(ServerPasswordCallback.class);
10. @Override
11. public void handle(Callback\[] callbacks) throws IOException,
12. UnsupportedCallbackException {
13. WSPasswordCallback pc = (WSPasswordCallback) callbacks\[0];
14. // 标识符
15. String identifier = pc.getIdentifier();
16. // 此处获取到的password为null，但是并不代表服务端没有拿到该属性。
17. String password = pc.getPassword();
18. logger.info("identifier:" + identifier);
19. logger.info("password:" + password);
20. if (identifier != null && identifier.equals("admin")) {
21. /\**
22. * 此处应该这样做：
23. * 1. 查询数据库，得到数据库中该用户名对应密码
24. * 2. 设置密码，wss4j会自动将你设置的密码 与客户端传递的密码进行匹配
25. * 3. 如果相同，则放行，否则返回权限不足信息
26. \*
27. \*/
28. pc.setPassword("password");
29. }else{
30. logger.info("未授权的用户");
31. }
32. }
33. }

 

 

server-beans.xml

 

Java代码  [![收藏代码](http://q269223.iteye.com/images/icon_star.png)]()

01. &lt;beans xmlns="http://www.springframework.org/schema/beans"
02. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cxf="http://cxf.apache.org/core"
03. xmlns:jaxws="http://cxf.apache.org/jaxws"
04. xsi:schemaLocation="http://www.springframework.org/schema/beans
05. http://www.springframework.org/schema/beans/spring-beans.xsd
06. http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
07. http://cxf.apache.org/jaxws
08. http://cxf.apache.org/schemas/jaxws.xsd"&gt;
09. &lt;!-- jar包中自带的cxf文件夹下的\*.xml文件 --&gt;
10. &lt;import resource="classpath:META-INF/cxf/cxf.xml" /&gt;
11. &lt;import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" /&gt;
12. &lt;import resource="classpath:META-INF/cxf/cxf-servlet.xml" /&gt;
13. &lt;bean id="myPasswordCallback" class="com.wss4j.interceptor.ServerPasswordCallback" /&gt;
14. &lt;jaxws:endpoint id="helloword" implementor="com.wss4j.server.HelloWorldImpl"
15. address="/helloService"&gt;
16. &lt;!-- 添加拦截器 --&gt;
17. &lt;jaxws:inInterceptors&gt;
18. &lt;bean class="org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor"&gt;
19. &lt;constructor-arg&gt;
20. &lt;map&gt;
21. &lt;entry key="action" value="UsernameToken" /&gt;
22. &lt;entry key="passwordType" value="PasswordText" /&gt;
23. &lt;entry key="signaturePropFile" value="..." /&gt;
24. &lt;entry key="user" value="FHDServer" /&gt;
25. &lt;entry key="passwordCallbackRef"&gt;
26. &lt;ref bean="myPasswordCallback" /&gt;
27. &lt;/entry&gt;
28. &lt;/map&gt;
29. &lt;/constructor-arg&gt;
30. &lt;/bean&gt;
31. &lt;/jaxws:inInterceptors&gt;
32. &lt;/jaxws:endpoint&gt;
33. &lt;/beans&gt;

 

 

beans.xml

 

Java代码  [![收藏代码](http://q269223.iteye.com/images/icon_star.png)]()

01. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
02. &lt;beans xmlns="http://www.springframework.org/schema/beans"
03. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
04. xmlns:jaxws="http://cxf.apache.org/jaxws"
05. xsi:schemaLocation="http://www.springframework.org/schema/beans
06. http://www.springframework.org/schema/beans/spring-beans.xsd
07. http://cxf.apache.org/jaxws
08. http://cxf.apache.org/schemas/jaxws.xsd"&gt;
09. &lt;import resource="../cxf/server-beans.xml"/&gt;
10. &lt;/beans&gt;

 

 

web.xml

 

Java代码  [![收藏代码](http://q269223.iteye.com/images/icon_star.png)]()

01. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
02. &lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
03. xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app\_2\_5.xsd"
04. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app\_3\_0.xsd"
05. id="WebApp\_ID" version="3.0"&gt;
06. &lt;display-name&gt;wss4j001-cxf-server&lt;/display-name&gt;
07. &lt;welcome-file-list&gt;
08. &lt;welcome-file&gt;index.html&lt;/welcome-file&gt;
09. &lt;welcome-file&gt;index.htm&lt;/welcome-file&gt;
10. &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;
11. &lt;welcome-file&gt;default.html&lt;/welcome-file&gt;
12. &lt;welcome-file&gt;default.htm&lt;/welcome-file&gt;
13. &lt;welcome-file&gt;default.jsp&lt;/welcome-file&gt;
14. &lt;/welcome-file-list&gt;
15. &lt;context-param&gt;
16. &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
17. &lt;param-value&gt;classpath:spring/beans.xml&lt;/param-value&gt;
18. &lt;/context-param&gt;
19. &lt;listener&gt;
20. &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
21. &lt;/listener&gt;
22. &lt;servlet&gt;
23. &lt;servlet-name&gt;CXFServlet&lt;/servlet-name&gt;
24. &lt;servlet-class&gt;org.apache.cxf.transport.servlet.CXFServlet&lt;/servlet-class&gt;
25. &lt;load-on-startup&gt;2&lt;/load-on-startup&gt;
26. &lt;/servlet&gt;
27. &lt;servlet-mapping&gt;
28. &lt;servlet-name&gt;CXFServlet&lt;/servlet-name&gt;
29. &lt;url-pattern&gt;/ws/\*&lt;/url-pattern&gt;
30. &lt;/servlet-mapping&gt;
31. &lt;/web-app&gt;

 

 

　　此时，我们的server端就已经搞定了。

       访问链接：http://localhost:8080/wss4j001-cxf-server/ws/helloService?wsdl

　　即可看到刚刚发布的webservice的wsdl文件。但是不能直接访问方法，因为我们为其增加了安全校验。

 

接下来，创建client 端 项目。

　　　

具体项目结构如下：

![](http://dl.iteye.com/upload/attachment/0081/8151/62eee04c-6eda-3fe5-8669-cb773f87ed27.jpg)  
 

HelloWorldClient.java

 

Java代码  [![收藏代码](http://q269223.iteye.com/images/icon_star.png)]()

01. package com.wss4j.client;
02. import org.springframework.context.support.ClassPathXmlApplicationContext;
03. import com.wss4j.server.HelloWorld;
04. public class HelloWorldClient {
05. public static void main(String\[] args) {
06. ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
07. new String\[] { "cxf/client-beans.xml" });
08. HelloWorld client = (HelloWorld) context.getBean("client");
09. String response = client.sayHello("Dan");
10. System.out.println("Response: " + response);
11. System.exit(0);
12. }
13. }

 

 

 

客户端添加用户认证拦截器 ClientPasswordCallback.java

 

Java代码  [![收藏代码](http://q269223.iteye.com/images/icon_star.png)]()

01. package com.wss4j.interceptor;
02. import java.io.IOException;
03. import javax.security.auth.callback.Callback;
04. import javax.security.auth.callback.CallbackHandler;
05. import javax.security.auth.callback.UnsupportedCallbackException;
06. import org.apache.ws.security.WSPasswordCallback;
07. public class ClientPasswordCallback implements CallbackHandler {
08. @Override
09. public void handle(Callback\[] callbacks) throws IOException,
10. UnsupportedCallbackException {
11. WSPasswordCallback pc = (WSPasswordCallback) callbacks\[0];
12. String ident = "admin";
13. String passwd = "password";
14. pc.setPassword(passwd);
15. pc.setIdentifier(ident);
16. }
17. }

 

 

client-beans.xml

 

Java代码  [![收藏代码](http://q269223.iteye.com/images/icon_star.png)]()

01. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
02. &lt;beans xmlns="http://www.springframework.org/schema/beans"
03. xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:cxf="http://cxf.apache.org/core"
04. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
05. xsi:schemaLocation="
06. http://www.springframework.org/schema/beans
07. http://www.springframework.org/schema/beans/spring-beans.xsd
08. http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
09. http://cxf.apache.org/jaxws
10. http://cxf.apache.org/schemas/jaxws.xsd"&gt;
11. &lt;bean id="clientPasswordCallback" class="com.wss4j.interceptor.ClientPasswordCallback" /&gt;
12. &lt;jaxws:client id="client" serviceClass="com.wss4j.server.HelloWorld"
13. address="http://localhost:8080/wss4j001-cxf-server/ws/helloService"&gt;
14. &lt;jaxws:outInterceptors&gt;
15. &lt;bean class="org.apache.cxf.interceptor.LoggingOutInterceptor" /&gt;
16. &lt;bean class="org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor"&gt;
17. &lt;constructor-arg&gt;
18. &lt;map&gt;
19. &lt;entry key="action" value="UsernameToken" /&gt;
20. &lt;entry key="passwordType" value="PasswordText" /&gt;
21. &lt;entry key="user" value="FHDClient" /&gt;
22. &lt;entry key="passwordCallbackRef"&gt;
23. &lt;ref bean="clientPasswordCallback" /&gt;
24. &lt;/entry&gt;
25. &lt;/map&gt;
26. &lt;/constructor-arg&gt;
27. &lt;/bean&gt;
28. &lt;/jaxws:outInterceptors&gt;
29. &lt;/jaxws:client&gt;
30. &lt;/beans&gt;

 

 

接下来，我们需要通过wsdl 生成服务端webservice的客户端java文件。这里使用cxf的wsdl2java命令。

 

打开cmd命令行：

      1. 进入到 \\apache-cxf-2.7.3\\apache-cxf-2.7.3\\bin 目录下

     

       2. 执行命令：

               wsdl2ava  -client http://localhost:8080/wss4j001-cxf-server/ws/helloService?wsdl          

 

     3. 生成的java文件就在 \\apache-cxf-2.7.3\\apache-cxf-2.7.3\\bin 目录下，名为com的文件夹。复制文件夹至client项目的src下。

 

 

　　接下来，首先将server项目添加到服务器中，启动服务器。然后执行 HelloWorldClient.java中的main方法，就可以访问服务端的webservice了，是不是so easy  ^\_^ ..