我的家園

          我的家園

          注意:以下客戶端調(diào)用代碼中獲取服務(wù)端ws實(shí)例,都是通過(guò)CXF 入門: 遠(yuǎn)程接口調(diào)用方式實(shí)現(xiàn)

          ?

          直入正題!

          以下是服務(wù)端配置

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

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

          <?xml version="1.0" encoding="UTF-8"?>
          <!DOCTYPE web-app
              PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
              "http://java.sun.com/dtd/web-app_2_3.dtd">
          <web-app>
          	<context-param>
          		<param-name>contextConfigLocation</param-name>
          		<!--ws-context.xml(必須)是cxf配置文件, wssec.xml可選,作用可以打印出加密信息類容 -->
          		<param-value>WEB-INF/ws-context.xml,WEB-INF/wssec.xml</param-value>
          	</context-param>
          
          	<listener>
          		<listener-class>
          			org.springframework.web.context.ContextLoaderListener
          		</listener-class>
          	</listener>
          
          	<servlet>
          		<servlet-name>CXFServlet</servlet-name>
          		<display-name>CXF Servlet</display-name>
          		<servlet-class>
          			org.apache.cxf.transport.servlet.CXFServlet
          		</servlet-class>
          		<load-on-startup>0</load-on-startup>
          	</servlet>
          
          	<servlet-mapping>
          		<servlet-name>CXFServlet</servlet-name>
          		<url-pattern>/services/*</url-pattern>
          	</servlet-mapping>
          </web-app>

          ?二,ws具體代碼
          簡(jiǎn)單的接口

          ?

          import javax.jws.WebService;
          
          @WebService()
          public interface WebServiceSample {
          	String say(String name);
          
          }
          

          ?

          ?

          接口具體實(shí)現(xiàn)類

          ?

          public class WebServiceSampleImpl implements WebServiceSample {
          
          	public String say(String name) {
          		return "你好," + name;
          	}
          }
          ?

          ?

          ?

          三,ws回調(diào)函數(shù),必須實(shí)現(xiàn)javax.security.auth.callback.CallbackHandler

          從cxf2.4.x后校驗(yàn)又cxf內(nèi)部實(shí)現(xiàn)校驗(yàn),所以不必自己校驗(yàn)password是否相同,但客戶端必須設(shè)置,詳情請(qǐng)參考:http://cxf.apache.org/docs/24-migration-guide.html的Runtime ?Changes片段

          ?

          回調(diào)函數(shù)WsAuthHandler代碼,校驗(yàn)客戶端請(qǐng)求是否合法 ,合法就放行,否則拒絕執(zhí)行任何操作

          ?

          import java.io.IOException;
          import javax.security.auth.callback.Callback;
          import javax.security.auth.callback.CallbackHandler;
          import javax.security.auth.callback.UnsupportedCallbackException;
          import org.apache.cxf.interceptor.Fault;
          import org.apache.ws.security.WSPasswordCallback;
          import org.apache.xmlbeans.impl.soap.SOAPException;
          
          public class WsAuthHandler implements CallbackHandler {
          
          	public void handle(Callback[] callbacks) throws IOException,
          			UnsupportedCallbackException {
          		for (int i = 0; i < callbacks.length; i++) {
          			WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
          			String identifier = pc.getIdentifier();
          			int usage = pc.getUsage();
          			if (usage == WSPasswordCallback.USERNAME_TOKEN) {// 密鑰方式USERNAME_TOKEN
          				// username token pwd...
          				// ▲這里的值必須和客戶端設(shè)的值相同,從cxf2.4.x后校驗(yàn)方式改為cxf內(nèi)部實(shí)現(xiàn)校驗(yàn),不必自己比較password是否相同
          				// 請(qǐng)參考:http://cxf.apache.org/docs/24-migration-guide.html的Runtime
          				// Changes片段
          				pc.setPassword("testPassword");// ▲【這里非常重要】▲
          				// ▲PS 如果和客戶端不同將拋出org.apache.ws.security.WSSecurityException:
          				// The
          				// security token could not be authenticated or
          				// authorized異常,服務(wù)端會(huì)認(rèn)為客戶端為非法調(diào)用
          			} else if (usage == WSPasswordCallback.SIGNATURE) {// 密鑰方式SIGNATURE
          				// set the password for client's keystore.keyPassword
          				// ▲這里的值必須和客戶端設(shè)的值相同,從cxf2.4.x后校驗(yàn)方式改為cxf內(nèi)部實(shí)現(xiàn)校驗(yàn),不必自己比較password是否相同;
          				// 請(qǐng)參考:http://cxf.apache.org/docs/24-migration-guide.html的Runtime
          				// Changes片段
          				pc.setPassword("testPassword");// //▲【這里非常重要】▲
          				// ▲PS:如果和客戶端不同將拋出org.apache.ws.security.WSSecurityException:The
          				// security token could not be authenticated or
          				// authorized異常,服務(wù)端會(huì)認(rèn)為客戶端為非法調(diào)用
          			}
          			//不用做其他操作
          		}
          	}
          }
          
          ?

          ?

          四,CXF配置ws-context.xml:

          ?

          <?xml version="1.0" encoding="UTF-8"?>
          <beans xmlns="http://www.springframework.org/schema/beans"
          	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
          	xsi:schemaLocation="
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
          http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
          
          	<import resource="classpath:META-INF/cxf/cxf.xml" />
          	<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
          	<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
          	<!-- 以上未基本配置,必須,位置在cxf jar中 -->
          	<jaxws:endpoint id="webServiceSample" address="/WebServiceSample"
          		implementor="com.service.impl.WebServiceSampleImpl">
          		<!--inInterceptors表示被外部調(diào)用時(shí),調(diào)用此攔截器 -->
          		<jaxws:inInterceptors>
          			<bean class="org.apache.cxf.binding.soap.saaj.SAAJInInterceptor" />
          			<bean class="org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor">
          				<constructor-arg>
          					<map>
          						<!-- 設(shè)置加密類型 -->
          						<entry key="action" value="UsernameToken" />
          						<!-- 設(shè)置密碼類型為明文 -->
          						<entry key="passwordType" value="PasswordText" />
          						<!--<entry key="action" value="UsernameToken Timestamp" /> 設(shè)置密碼類型為加密<entry 
          							key="passwordType" value="PasswordDigest" /> -->
          						<entry key="passwordCallbackClass" value="com.service.handler.WsAuthHandler" />
          					</map>
          				</constructor-arg>
          			</bean>
          		</jaxws:inInterceptors>
          	</jaxws:endpoint>
          </beans>
          

          ?

          ?

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

          ?

          <?xml version="1.0" encoding="UTF-8"?>
          <beans xmlns="http://www.springframework.org/schema/beans"
          	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cxf="http://cxf.apache.org/core"
          	xmlns:wsa="http://cxf.apache.org/ws/addressing" xmlns:http="http://cxf.apache.org/transports/http/configuration"
          	xmlns:wsrm-policy="http://schemas.xmlsoap.org/ws/2005/02/rm/policy"
          	xmlns:wsrm-mgr="http://cxf.apache.org/ws/rm/manager"
          	xsi:schemaLocation="
                 http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
                 http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd
                 http://schemas.xmlsoap.org/ws/2005/02/rm/policy http://schemas.xmlsoap.org/ws/2005/02/rm/wsrm-policy.xsd
                 http://cxf.apache.org/ws/rm/manager http://cxf.apache.org/schemas/configuration/wsrm-manager.xsd
                 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
          	<cxf:bus>
          		<cxf:features>
          			<cxf:logging />
          			<wsa:addressing />
          		</cxf:features>
          	</cxf:bus>
          </beans>

          ?

          服務(wù)端代碼及配置到此結(jié)束?。?!

          ?

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

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

          以下是客戶端配置,主要是回調(diào)函數(shù),在客戶端調(diào)用服務(wù)端前被調(diào)用,負(fù)責(zé)安全信息的設(shè)置

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

          ?

          ?

          一,先實(shí)現(xiàn)回調(diào)函數(shù)WsClinetAuthHandler,同樣必須實(shí)現(xiàn)javax.security.auth.callback.CallbackHandler

          import java.io.IOException;
          import javax.security.auth.callback.Callback;
          import javax.security.auth.callback.CallbackHandler;
          import javax.security.auth.callback.UnsupportedCallbackException;
          import org.apache.ws.security.WSPasswordCallback;
          
          public class WsClinetAuthHandler implements CallbackHandler {
          
          	public void handle(Callback[] callbacks) throws IOException,
          			UnsupportedCallbackException {
          		for (int i = 0; i < callbacks.length; i++) {
          			WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
          			System.out.println("identifier: " + pc.getIdentifier());
          			// 這里必須設(shè)置密碼,否則會(huì)拋出:java.lang.IllegalArgumentException: pwd == null
          			// but a password is needed
          			pc.setPassword("testPassword");// ▲【這里必須設(shè)置密碼】▲
          		}
          	}
          }
          ?

          二,客戶端調(diào)用代碼:

          ?

          import java.util.ArrayList;
          import java.util.HashMap;
          import java.util.Map;
          
          import org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor;
          import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
          import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor;
          import org.apache.ws.security.WSConstants;
          import org.apache.ws.security.handler.WSHandlerConstants;
          
          import test.saa.client.WebServiceSample;
          import test.saa.handler.WsClinetAuthHandler;
          
          public class TestClient {
          
          	public static void main(String[] args) {
          		// 以下和服務(wù)端配置類似,不對(duì),應(yīng)該說(shuō)服務(wù)端和這里的安全驗(yàn)證配置一致
          		Map<String, Object> outProps = new HashMap<String, Object>();
          		outProps.put(WSHandlerConstants.ACTION,
          				WSHandlerConstants.USERNAME_TOKEN);
          		outProps.put(WSHandlerConstants.USER, "admin");
          		outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);
          		// 指定在調(diào)用遠(yuǎn)程ws之前觸發(fā)的回調(diào)函數(shù)WsClinetAuthHandler,其實(shí)類似于一個(gè)攔截器
          		outProps.put(WSHandlerConstants.PW_CALLBACK_CLASS,
          				WsClinetAuthHandler.class.getName());
          		ArrayList list = new ArrayList();
          		// 添加cxf安全驗(yàn)證攔截器,必須
          		list.add(new SAAJOutInterceptor());
          		list.add(new WSS4JOutInterceptor(outProps));
          
          		JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
          		// WebServiceSample服務(wù)端接口實(shí)現(xiàn)類,這里并不是直接把服務(wù)端的類copy過(guò)來(lái),具體請(qǐng)參考http://learning.iteye.com/blog/1333223
          		factory.setServiceClass(WebServiceSample.class);
          		// 設(shè)置ws訪問(wèn)地址
          		factory.setAddress("http://localhost:8080/cxf-wssec/services/WebServiceSample");
                  //注入攔截器,用于加密安全驗(yàn)證信息
          		factory.getOutInterceptors().addAll(list);
          		WebServiceSample service = (WebServiceSample) factory.create();
          		String response = service.say("2012");
          		System.out.println(response);
          	}
          }

          ?客戶端到此結(jié)束?。。?!

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

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

          ?

          PS:客戶端的另一種調(diào)用方式,主要通過(guò)配置文件,不過(guò)需要spring bean的配置文件(第一種就不用牽扯到spring的配置,比較通用吧?。?/h2>

          ?

          一,回調(diào)函數(shù)WsClinetAuthHandler不變,和上面一樣
          二,client-beans.xml安全驗(yàn)證配置文件,具體信息看注釋,如下:

          ?

          <?xml version="1.0" encoding="UTF-8"?>
          <beans xmlns="http://www.springframework.org/schema/beans"
          	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
          	xsi:schemaLocation="
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
          http://cxf.apache.org/jaxws http://cxf.apache.org/schema/jaxws.xsd">
          <!--這里無(wú)非是通過(guò)配置來(lái)替代JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean()創(chuàng)建代理并實(shí)例化一個(gè)ws-->
          	<bean id="client" class="test.saa.client.WebServiceSample"
          		factory-bean="clientFactory" factory-method="create" />
          	<!-- 通過(guò)代理創(chuàng)建ws實(shí)例 -->
          	<bean id="clientFactory" class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean">
          		<property name="serviceClass" value="test.saa.client.WebServiceSample" />
          		<!-- ws地址,也可以是完整的wsdl地址 -->
          		<property name="address"
          			value="http://localhost:8080/cxf-wssec/services/WebServiceSample" />
          		<!--outInterceptors表示調(diào)用外部指定ws時(shí),調(diào)用此攔截器 -->
          		<property name="outInterceptors">
          			<list>
          				<bean class="org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor" />
          				<ref bean="wss4jOutConfiguration" />
          			</list>
          		</property>
          	</bean>
          
          	<bean id="wss4jOutConfiguration" class="org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor">
          		<property name="properties">
          			<map>
          				<!-- 設(shè)置加密類型 ,服務(wù)端需要和這里的設(shè)置保持一致-->
          				<entry key="action" value="UsernameToken" />
          				<entry key="user" value="admin" />
          				<!-- 設(shè)置密碼為明文 ,服務(wù)端需要和這里的設(shè)置保持一致-->
          				<entry key="passwordType" value="PasswordText" />
          				<!-- <entry key="action" value="UsernameToken Timestamp" /> <entry key="user" 
          					value="adminTest" /> 設(shè)置密碼類型為加密方式,服務(wù)端需要和這里的設(shè)置保持一致<entry key="passwordType" value="PasswordDigest" 
          					/> -->
          				<entry key="passwordCallbackRef">
          					<ref bean="passwordCallback" />
          				</entry>
          			</map>
          		</property>
          	</bean>
          	<bean id="passwordCallback" class="test.saa.handler.WsClinetAuthHandler" />
          </beans>

          ?
          三,具體調(diào)用服務(wù)端代碼:

          ?

          import org.springframework.context.ApplicationContext;
          import org.springframework.context.support.ClassPathXmlApplicationContext;
          
          import test.saa.client.WebServiceSample;
          
          public final class Client {
          
          	public static void main(String args[]) throws Exception {
          	//加載配置
          		ApplicationContext context = new ClassPathXmlApplicationContext(
          				new String[] { "test/saa/client-beans.xml" });
                  //獲取ws實(shí)例
          		WebServiceSample client = (WebServiceSample) context.getBean("client");
          		String response = client.say("2012");
          		System.out.println("Response: " + response);
          	}
          }

          ?
          到此客戶端第二種實(shí)現(xiàn)方式結(jié)束
          GOOD LUCKY!!!
          如有不明,請(qǐng)指教?。?!






          Feedback

          # re: CXF 入門:創(chuàng)建一個(gè)基于WS-Security標(biāo)準(zhǔn)的安全驗(yàn)證(CXF回調(diào)函數(shù)使用,)[未登錄](méi)  回復(fù)  更多評(píng)論   

          2015-06-11 16:39 by hello
          好文章!

          # re: CXF 入門:創(chuàng)建一個(gè)基于WS-Security標(biāo)準(zhǔn)的安全驗(yàn)證(CXF回調(diào)函數(shù)使用,)  回復(fù)  更多評(píng)論   

          2015-06-24 14:49 by qping
          謝謝~

          # re: CXF 入門:創(chuàng)建一個(gè)基于WS-Security標(biāo)準(zhǔn)的安全驗(yàn)證(CXF回調(diào)函數(shù)使用,)  回復(fù)  更多評(píng)論   

          2016-07-15 11:16 by 李虎鵬
          @qping
          寫的真好,項(xiàng)目中要用,我試了一下,可以!萬(wàn)分感謝!!!

          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 商南县| 珲春市| 岢岚县| 延吉市| 蚌埠市| 望奎县| 祁连县| 高唐县| 河北省| 商水县| 托克托县| 平远县| 从化市| 永寿县| 博客| 兴城市| 沂水县| 邓州市| 荆门市| 章丘市| 安阳市| 宁都县| 随州市| 长治县| 石河子市| 尚义县| 东安县| 清流县| 临沧市| 平阳县| 成都市| 诏安县| 柳州市| 伊金霍洛旗| 冀州市| 托克托县| 普格县| 嵩明县| 古交市| 乡宁县| 莒南县|