CXF 入門:建立一個基于WS-Security标準的安全驗證
http://www.blogjava.net/zljpp/archive/2012/04/15/374371.html
以下是服務端配置
========================================================
一,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片段
回調函數WsAuthHandler代碼,校驗用戶端請求是否合法 ,合法就放行,否則拒絕執行任何操作
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>
服務端代碼及配置到此結束!!!
=========================================================
=========================================================
以下是用戶端配置,主要是回調函數,在用戶端調用服務端前被調用,負責安全資訊的設定
----------------------------------------------------------------------------------------
一,先實作回調函數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);
}
}
用戶端到此結束!!!!
========================================================================
#######################################################################
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!!!
如有不明,請指教!!!