1. 程式人生 > >CXF 入門:創建一個基於WS-Security標準的安全驗證(CXF回調函數使用)

CXF 入門:創建一個基於WS-Security標準的安全驗證(CXF回調函數使用)

urn star cti say struct stc lba features ear

註意:以下客戶端調用代碼中獲取服務端ws實例,都是通過CXF 入門: 遠程接口調用方式實現

以下是服務端配置

========================================================

一,web.xml配置,具體不在詳述

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE web-app
  3. PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  4. "http://java.sun.com/dtd/web-app_2_3.dtd">
  5. <web-app>
  6. <context-param>
  7. <param-name>contextConfigLocation</param-name>
  8. <!--ws-context.xml(必須)是cxf配置文件, wssec.xml可選,作用可以打印出加密信息類容 -->
  9. <param-value>WEB-INF/ws-context.xml,WEB-INF/wssec.xml</param-value>
  10. </context-param>
  11. <listener>
  12. <listener-class>
  13. org.springframework.web.context.ContextLoaderListener
  14. </listener-class>
  15. </listener>
  16. <servlet>
  17. <servlet-name>CXFServlet</servlet-name>
  18. <display-name>CXF Servlet</display-name>
  19. <servlet-class>
  20. org.apache.cxf.transport.servlet.CXFServlet
  21. </servlet-class>
  22. <load-on-startup>0</load-on-startup>
  23. </servlet>
  24. <servlet-mapping>
  25. <servlet-name>CXFServlet</servlet-name>
  26. <url-pattern>/services/*</url-pattern>
  27. </servlet-mapping>
  28. </web-app>

二,ws具體代碼
簡單的接口

  1. import javax.jws.WebService;
  2. @WebService()
  3. public interface WebServiceSample {
  4. String say(String name);
  5. }

接口具體實現類

  1. public class WebServiceSampleImpl implements WebServiceSample {
  2. public String say(String name) {
  3. return "你好," + name;
  4. }
  5. }

三,ws回調函數,必須實現javax.security.auth.callback.CallbackHandler

從cxf2.4.x後校驗又cxf內部實現校驗,所以不必自己校驗password是否相同,但客戶端必須設置,詳情請參考:http://cxf.apache.org/docs/24-migration-guide.html的Runtime Changes片段

回調函數WsAuthHandler代碼,校驗客戶端請求是否合法 ,合法就放行,否則拒絕執行任何操作

  1. import java.io.IOException;
  2. import javax.security.auth.callback.Callback;
  3. import javax.security.auth.callback.CallbackHandler;
  4. import javax.security.auth.callback.UnsupportedCallbackException;
  5. import org.apache.cxf.interceptor.Fault;
  6. import org.apache.ws.security.WSPasswordCallback;
  7. import org.apache.xmlbeans.impl.soap.SOAPException;
  8. public class WsAuthHandler implements CallbackHandler {
  9. public void handle(Callback[] callbacks) throws IOException,
  10. UnsupportedCallbackException {
  11. for (int i = 0; i < callbacks.length; i++) {
  12. WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
  13. String identifier = pc.getIdentifier();
  14. int usage = pc.getUsage();
  15. if (usage == WSPasswordCallback.USERNAME_TOKEN) {// 密鑰方式USERNAME_TOKEN
  16. // username token pwd...
  17. // ▲這裏的值必須和客戶端設的值相同,從cxf2.4.x後校驗方式改為cxf內部實現校驗,不必自己比較password是否相同
  18. // 請參考:http://cxf.apache.org/docs/24-migration-guide.html的Runtime
  19. // Changes片段
  20. pc.setPassword("testPassword");// ▲【這裏非常重要】▲
  21. // ▲PS 如果和客戶端不同將拋出org.apache.ws.security.WSSecurityException:
  22. // The
  23. // security token could not be authenticated or
  24. // authorized異常,服務端會認為客戶端為非法調用
  25. } else if (usage == WSPasswordCallback.SIGNATURE) {// 密鑰方式SIGNATURE
  26. // set the password for client‘s keystore.keyPassword
  27. // ▲這裏的值必須和客戶端設的值相同,從cxf2.4.x後校驗方式改為cxf內部實現校驗,不必自己比較password是否相同;
  28. // 請參考:http://cxf.apache.org/docs/24-migration-guide.html的Runtime
  29. // Changes片段
  30. pc.setPassword("testPassword");// //▲【這裏非常重要】▲
  31. // ▲PS:如果和客戶端不同將拋出org.apache.ws.security.WSSecurityException:The
  32. // security token could not be authenticated or
  33. // authorized異常,服務端會認為客戶端為非法調用
  34. }
  35. //不用做其他操作
  36. }
  37. }
  38. }

四,CXF配置ws-context.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
  4. xsi:schemaLocation="
  5. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  6. http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
  7. <import resource="classpath:META-INF/cxf/cxf.xml" />
  8. <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
  9. <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
  10. <!-- 以上未基本配置,必須,位置在cxf jar中 -->
  11. <jaxws:endpoint id="webServiceSample" address="/WebServiceSample"
  12. implementor="com.service.impl.WebServiceSampleImpl">
  13. <!--inInterceptors表示被外部調用時,調用此攔截器 -->
  14. <jaxws:inInterceptors>
  15. <bean class="org.apache.cxf.binding.soap.saaj.SAAJInInterceptor" />
  16. <bean class="org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor">
  17. <constructor-arg>
  18. <map>
  19. <!-- 設置加密類型 -->
  20. <entry key="action" value="UsernameToken" />
  21. <!-- 設置密碼類型為明文 -->
  22. <entry key="passwordType" value="PasswordText" />
  23. <!--<entry key="action" value="UsernameToken Timestamp" /> 設置密碼類型為加密<entry
  24. key="passwordType" value="PasswordDigest" /> -->
  25. <entry key="passwordCallbackClass" value="com.service.handler.WsAuthHandler" />
  26. </map>
  27. </constructor-arg>
  28. </bean>
  29. </jaxws:inInterceptors>
  30. </jaxws:endpoint>
  31. </beans>

CXF配置wssec.xml(可選),用於配置輸出校驗的具體信息

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cxf="http://cxf.apache.org/core"
  4. xmlns:wsa="http://cxf.apache.org/ws/addressing" xmlns:http="http://cxf.apache.org/transports/http/configuration"
  5. xmlns:wsrm-policy="http://schemas.xmlsoap.org/ws/2005/02/rm/policy"
  6. xmlns:wsrm-mgr="http://cxf.apache.org/ws/rm/manager"
  7. xsi:schemaLocation="
  8. http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
  9. http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd
  10. http://schemas.xmlsoap.org/ws/2005/02/rm/policy http://schemas.xmlsoap.org/ws/2005/02/rm/wsrm-policy.xsd
  11. http://cxf.apache.org/ws/rm/manager http://cxf.apache.org/schemas/configuration/wsrm-manager.xsd
  12. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  13. <cxf:bus>
  14. <cxf:features>
  15. <cxf:logging />
  16. <wsa:addressing />
  17. </cxf:features>
  18. </cxf:bus>
  19. </beans>

服務端代碼及配置到此結束!!!

=========================================================

=========================================================

以下是客戶端配置,主要是回調函數,在客戶端調用服務端前被調用,負責安全信息的設置

----------------------------------------------------------------------------------------

一,先實現回調函數WsClinetAuthHandler,同樣必須實現javax.security.auth.callback.CallbackHandler

  1. import java.io.IOException;
  2. import javax.security.auth.callback.Callback;
  3. import javax.security.auth.callback.CallbackHandler;
  4. import javax.security.auth.callback.UnsupportedCallbackException;
  5. import org.apache.ws.security.WSPasswordCallback;
  6. public class WsClinetAuthHandler implements CallbackHandler {
  7. public void handle(Callback[] callbacks) throws IOException,
  8. UnsupportedCallbackException {
  9. for (int i = 0; i < callbacks.length; i++) {
  10. WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
  11. System.out.println("identifier: " + pc.getIdentifier());
  12. // 這裏必須設置密碼,否則會拋出:java.lang.IllegalArgumentException: pwd == null
  13. // but a password is needed
  14. pc.setPassword("testPassword");// ▲【這裏必須設置密碼】▲
  15. }
  16. }
  17. }

二,客戶端調用代碼:

  1. import java.util.ArrayList;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor;
  5. import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
  6. import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor;
  7. import org.apache.ws.security.WSConstants;
  8. import org.apache.ws.security.handler.WSHandlerConstants;
  9. import test.saa.client.WebServiceSample;
  10. import test.saa.handler.WsClinetAuthHandler;
  11. public class TestClient {
  12. public static void main(String[] args) {
  13. // 以下和服務端配置類似,不對,應該說服務端和這裏的安全驗證配置一致
  14. Map<String, Object> outProps = new HashMap<String, Object>();
  15. outProps.put(WSHandlerConstants.ACTION,
  16. WSHandlerConstants.USERNAME_TOKEN);
  17. outProps.put(WSHandlerConstants.USER, "admin");
  18. outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);
  19. // 指定在調用遠程ws之前觸發的回調函數WsClinetAuthHandler,其實類似於一個攔截器
  20. outProps.put(WSHandlerConstants.PW_CALLBACK_CLASS,
  21. WsClinetAuthHandler.class.getName());
  22. ArrayList list = new ArrayList();
  23. // 添加cxf安全驗證攔截器,必須
  24. list.add(new SAAJOutInterceptor());
  25. list.add(new WSS4JOutInterceptor(outProps));
  26. JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
  27. // WebServiceSample服務端接口實現類,這裏並不是直接把服務端的類copy過來,具體請參考http://learning.iteye.com/blog/1333223
  28. factory.setServiceClass(WebServiceSample.class);
  29. // 設置ws訪問地址
  30. factory.setAddress("http://localhost:8080/cxf-wssec/services/WebServiceSample");
  31. //註入攔截器,用於加密安全驗證信息
  32. factory.getOutInterceptors().addAll(list);
  33. WebServiceSample service = (WebServiceSample) factory.create();
  34. String response = service.say("2012");
  35. System.out.println(response);
  36. }
  37. }

客戶端到此結束!!!!

========================================================================

#######################################################################

PS:客戶端的另一種調用方式,主要通過配置文件,不過需要spring bean的配置文件(第一種就不用牽扯到spring的配置,比較通用吧!)

一,回調函數WsClinetAuthHandler不變,和上面一樣
二,client-beans.xml安全驗證配置文件,具體信息看註釋,如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
  4. xsi:schemaLocation="
  5. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
  6. http://cxf.apache.org/jaxws http://cxf.apache.org/schema/jaxws.xsd">
  7. <!--這裏無非是通過配置來替代JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean()創建代理並實例化一個ws-->
  8. <bean id="client" class="test.saa.client.WebServiceSample"
  9. factory-bean="clientFactory" factory-method="create" />
  10. <!-- 通過代理創建ws實例 -->
  11. <bean id="clientFactory" class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean">
  12. <property name="serviceClass" value="test.saa.client.WebServiceSample" />
  13. <!-- ws地址,也可以是完整的wsdl地址 -->
  14. <property name="address"
  15. value="http://localhost:8080/cxf-wssec/services/WebServiceSample" />
  16. <!--outInterceptors表示調用外部指定ws時,調用此攔截器 -->
  17. <property name="outInterceptors">
  18. <list>
  19. <bean class="org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor" />
  20. <ref bean="wss4jOutConfiguration" />
  21. </list>
  22. </property>
  23. </bean>
  24. <bean id="wss4jOutConfiguration" class="org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor">
  25. <property name="properties">
  26. <map>
  27. <!-- 設置加密類型 ,服務端需要和這裏的設置保持一致-->
  28. <entry key="action" value="UsernameToken" />
  29. <entry key="user" value="admin" />
  30. <!-- 設置密碼為明文 ,服務端需要和這裏的設置保持一致-->
  31. <entry key="passwordType" value="PasswordText" />
  32. <!-- <entry key="action" value="UsernameToken Timestamp" /> <entry key="user"
  33. value="adminTest" /> 設置密碼類型為加密方式,服務端需要和這裏的設置保持一致<entry key="passwordType" value="PasswordDigest"
  34. /> -->
  35. <entry key="passwordCallbackRef">
  36. <ref bean="passwordCallback" />
  37. </entry>
  38. </map>
  39. </property>
  40. </bean>
  41. <bean id="passwordCallback" class="test.saa.handler.WsClinetAuthHandler" />
  42. </beans>


三,具體調用服務端代碼:

    1. import org.springframework.context.ApplicationContext;
    2. import org.springframework.context.support.ClassPathXmlApplicationContext;
    3. import test.saa.client.WebServiceSample;
    4. public final class Client {
    5. public static void main(String args[]) throws Exception {
    6. //加載配置
    7. ApplicationContext context = new ClassPathXmlApplicationContext(
    8. new String[] { "test/saa/client-beans.xml" });
    9. //獲取ws實例
    10. WebServiceSample client = (WebServiceSample) context.getBean("client");
    11. String response = client.say("2012");
    12. System.out.println("Response: " + response);
    13. }
    14. }

CXF 入門:創建一個基於WS-Security標準的安全驗證(CXF回調函數使用)