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

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

 

直入正題!

如下是服務端配置java

========================================================web

一,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具體代碼
簡單的接口

 

import javax.jws.WebService;

@WebService()
public interface WebServiceSample {
	String say(String name);

}

 

 

接口具體實現類

 

public class WebServiceSampleImpl implements WebServiceSample {

	public String say(String name) {
		return "你好," + name;
	}
}

 

 

 

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

從cxf2.4.x後校驗又cxf內部實現校驗,因此沒必要本身校驗password是否相同,但客戶端必須設置,詳情請參考:http://cxf.apache.org/docs/24-migration-guide.html的Runtime  Changes片斷spring

 

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

 

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...
				// ▲這裏的值必須和客戶端設的值相同,從cxf2.4.x後校驗方式改成cxf內部實現校驗,沒必要本身比較password是否相同
				// 請參考: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異常,服務端會認爲客戶端爲非法調用
			} else if (usage == WSPasswordCallback.SIGNATURE) {// 密鑰方式SIGNATURE
				// set the password for client's keystore.keyPassword
				// ▲這裏的值必須和客戶端設的值相同,從cxf2.4.x後校驗方式改成cxf內部實現校驗,沒必要本身比較password是否相同;
				// 請參考: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異常,服務端會認爲客戶端爲非法調用
			}
			//不用作其餘操做
		}
	}
}

 

 

四,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表示被外部調用時,調用此攔截器 -->
		<jaxws:inInterceptors>
			<bean class="org.apache.cxf.binding.soap.saaj.SAAJInInterceptor" />
			<bean class="org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor">
				<constructor-arg>
					<map>
						<!-- 設置加密類型 -->
						<entry key="action" value="UsernameToken" />
						<!-- 設置密碼類型爲明文 -->
						<entry key="passwordType" value="PasswordText" />
						<!--<entry key="action" value="UsernameToken Timestamp" /> 設置密碼類型爲加密<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(可選),用於配置輸出校驗的具體信息

 

<?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>

 

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

 

=========================================================app

=========================================================ide

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

----------------------------------------------------------------------------------------函數

 

 

一,先實現回調函數WsClinetAuthHandler,一樣必須實現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());
			// 這裏必須設置密碼,不然會拋出:java.lang.IllegalArgumentException: pwd == null
			// but a password is needed
			pc.setPassword("testPassword");// ▲【這裏必須設置密碼】▲
		}
	}
}
 

二,客戶端調用代碼:

 

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) {
		// 如下和服務端配置相似,不對,應該說服務端和這裏的安全驗證配置一致
		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);
		// 指定在調用遠程ws以前觸發的回調函數WsClinetAuthHandler,其實相似於一個攔截器
		outProps.put(WSHandlerConstants.PW_CALLBACK_CLASS,
				WsClinetAuthHandler.class.getName());
		ArrayList list = new ArrayList();
		// 添加cxf安全驗證攔截器,必須
		list.add(new SAAJOutInterceptor());
		list.add(new WSS4JOutInterceptor(outProps));

		JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
		// WebServiceSample服務端接口實現類,這裏並非直接把服務端的類copy過來,具體請參考http://learning.iteye.com/blog/1333223
		factory.setServiceClass(WebServiceSample.class);
		// 設置ws訪問地址
		factory.setAddress("http://localhost:8080/cxf-wssec/services/WebServiceSample");
        //注入攔截器,用於加密安全驗證信息
		factory.getOutInterceptors().addAll(list);
		WebServiceSample service = (WebServiceSample) factory.create();
		String response = service.say("2012");
		System.out.println(response);
	}
}

 客戶端到此結束!!!!ui

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

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

 

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

 

一,回調函數WsClinetAuthHandler不變,和上面同樣
二,client-beans.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-2.0.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schema/jaxws.xsd">
<!--這裏無非是經過配置來替代JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean()建立代理並實例化一個ws-->
	<bean id="client" class="test.saa.client.WebServiceSample"
		factory-bean="clientFactory" factory-method="create" />
	<!-- 經過代理建立ws實例 -->
	<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表示調用外部指定ws時,調用此攔截器 -->
		<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>
				<!-- 設置加密類型 ,服務端須要和這裏的設置保持一致-->
				<entry key="action" value="UsernameToken" />
				<entry key="user" value="admin" />
				<!-- 設置密碼爲明文 ,服務端須要和這裏的設置保持一致-->
				<entry key="passwordType" value="PasswordText" />
				<!-- <entry key="action" value="UsernameToken Timestamp" /> <entry key="user" 
					value="adminTest" /> 設置密碼類型爲加密方式,服務端須要和這裏的設置保持一致<entry key="passwordType" value="PasswordDigest" 
					/> -->
				<entry key="passwordCallbackRef">
					<ref bean="passwordCallback" />
				</entry>
			</map>
		</property>
	</bean>
	<bean id="passwordCallback" class="test.saa.handler.WsClinetAuthHandler" />
</beans>

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

 

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實例
		WebServiceSample client = (WebServiceSample) context.getBean("client");
		String response = client.say("2012");
		System.out.println("Response: " + response);
	}
}

 
到此客戶端第二種實現方式結束
GOOD LUCKY!!!
若有不明,請指教!!!

 

來源:http://www.blogjava.net/zljpp/archive/2012/04/15/374371.html

相關文章
相關標籤/搜索