一、服务器端:
1、权限判断:
package cn.tdtk.ws.interceptor;
import java.util.List;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/** 通过 AbstractPhaseInterceptor,可以指定拦截器在那个阶段起作用。 */
public class AuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
//表示该拦截器在调用之前拦截 “SOAP消息”。
public AuthInterceptor(){
super(Phase.PRE_INVOKE);
}
/**
* 实现自己的拦截器,需要实现handleMessage方法。该方法里面的参数就是被拦截到的消息,一旦拦截到消息,
* 那么剩下就是解析或修改SOAP消息。
*/
@Override
public void handleMessage(SoapMessage msg) throws Fault {
List<Header> headers = msg.getHeaders();
System.out.println(headers.size());
if(headers==null || headers.size()<1){
throw new Fault(new IllegalArgumentException("没有Header,不能调用"));
}
Header firstHeader = headers.get(0);
Element elements = (Element) firstHeader.getObject();
NodeList userids = elements.getElementsByTagName("username");
NodeList passwords = elements.getElementsByTagName("password");
if(userids.getLength()!=1)
throw new Fault(new IllegalArgumentException("用户名的格式不正确!"));
if(passwords.getLength()!=1)
throw new Fault(new IllegalArgumentException("密码的格式不正确!"));
String userid = userids.item(0).getTextContent();
String password = passwords.item(0).getTextContent();
//去数据库进行验证
if(!userid.equals("tom") || !password.equals("123")){
throw new Fault(new IllegalArgumentException("用户名或密码错误!"));
}
}
}
2、发布和添加拦截器:
package cn.tdtk.test;
import javax.xml.ws.Endpoint;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.EndpointImpl;
import cn.tdtk.ws.dao.impl.HelloWorldImpl;
import cn.tdtk.ws.interceptor.AuthInterceptor;
public class HelloWorldServiceTest {
public static void main(String[] args) {
/** 发布web service */
// Endpoint.publish("http://127.0.0.1:8080/helloService",
// new HelloWorldImpl());
//使用拦截器,信息会打印在控制台上
EndpointImpl end = (EndpointImpl)Endpoint.publish("http://127.0.0.1:8080/helloService", new HelloWorldImpl());
// end.getDataBinding().setMtomEnabled(true);
/** 添加In拦截器 */
end.getInInterceptors().add(new LoggingInInterceptor());
//添加Out拦截器
end.getOutInterceptors().add(new LoggingOutInterceptor());
/** 添加自定义拦截器 */
end.getInInterceptors().add(new AuthInterceptor());
System.out.println("web service publish success");
}
}
二、客户端:
1、要完成权限验证,那么客户端必须携带验证信息用户名和密码,这些信息可以防止Header里面:
package cn.tdtk.ws.interceptor;
import java.util.List;
import javax.xml.namespace.QName;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class AddHeaderInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
private String username;
private String password;
public AddHeaderInterceptor(String username,String password) {
super(Phase.PREPARE_SEND);//在发送之前进行拦截
this.username=username;
this.password=password;
}
@Override
public void handleMessage(SoapMessage msg) throws Fault {
List<Header> headers = msg.getHeaders();
System.out.println("============"+ headers);
Document doc = DOMUtils.createDocument();
Element hele = doc.createElement("authHeader");
//这里的username和password标签要和服务器端一致
Element uele = doc.createElement("username");
uele.setTextContent(username);
Element pele = doc.createElement("password");
pele.setTextContent(password);
hele.appendChild(uele);
hele.appendChild(pele);
//将创建的header添加到SOAP的Header里面
headers.add(new Header(new QName("tom"),hele));
/*
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<authHeader>
<username>tom</username>
<password>1223</password>
</authHeader>
</soap:Header>
<soap:Body>
<ns2:getAllCats xmlns:ns2="http://dao.ws.tdtk.cn/"/>
</soap:Body>
</soap:Envelope>
*/
}
}
2、客户端访问,此时就需要进行拦截:
package cn.tdtk.test;
import java.util.List;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import cn.tdtk.ws.dao.Cat;
import cn.tdtk.ws.dao.Entry;
import cn.tdtk.ws.dao.HelloWorld;
import cn.tdtk.ws.dao.StringCat;
import cn.tdtk.ws.dao.User;
import cn.tdtk.ws.dao.impl.HelloWorldImplService;
import cn.tdtk.ws.interceptor.AddHeaderInterceptor;
public class HelloWorldServiceTest {
/**
* @param args
*/
public static void main(String[] args) {
HelloWorldImplService factory= new HelloWorldImplService();
HelloWorld hw = factory.getHelloWorldImplPort();
//为客户端添加拦截器
Client cl = ClientProxy.getClient(hw);
cl.getInInterceptors().add(new LoggingInInterceptor());
//添加自定义拦截器
cl.getOutInterceptors().add(new AddHeaderInterceptor("tom","123"));
cl.getOutInterceptors().add(new LoggingOutInterceptor());
System.out.println("====================");
User us = new User();
us.setId(1);
us.setName("tom");
us.setPwd("123");
us.setAddress("shanghai");
List<Cat> lists = hw.getCatsByUser(us);
for(Cat cat : lists){
System.out.println("Name: "+cat.getName()+" : "+"Color: "+cat.getColor());
}
System.out.println("====================");
StringCat sc = hw.getAllCats();
for(Entry en : sc.getEntrys()){
System.out.println(en.getKey()+" : "+en.getValue().getName());
}
}
}
三、控制台上回打印出SOAP信息,从中可以看出在访问访问之前已经给SOAP信息添加了soap:Header消息,它携带用户名和密码。
2013-7-3 9:33:34 org.apache.cxf.services.HelloWorldImplService.HelloWorldImplPort.HelloWorld
信息: Outbound Message
---------------------------
ID: 1
Address: http://127.0.0.1:8080/helloService
Encoding: UTF-8
Content-Type: text/xml
Headers: {Accept=[*/*], SOAPAction=[""]}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header><authHeader><username>tom</username><password>123</password></authHeader></soap:Header><soap:Body><ns2:getCatsByUser xmlns:ns2="http://dao.ws.tdtk.cn/"><arg0><address>shanghai</address><id>1</id><name>tom</name><pwd>123</pwd></arg0></ns2:getCatsByUser></soap:Body></soap:Envelope>
--------------------------------------
2013-7-3 9:33:34 org.apache.cxf.services.HelloWorldImplService.HelloWorldImplPort.HelloWorld
信息: Inbound Message
----------------------------
ID: 1
Response-Code: 200
Encoding: UTF-8
Content-Type: text/xml;charset=UTF-8
Headers: {Content-Length=[403], content-type=[text/xml;charset=UTF-8], Server=[Jetty(7.5.4.v20111024)]}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:getCatsByUserResponse xmlns:ns2="http://dao.ws.tdtk.cn/"><return><color>橙色</color><id>1</id><name>机器猫</name></return><return><color>黑色</color><id>2</id><name>huanhuan</name></return><return><color>红色</color><id>3</id><name>xixi</name></return></ns2:getCatsByUserResponse></soap:Body></soap:Envelope>
--------------------------------------
Name: 机器猫 : Color: 橙色
Name: huanhuan : Color: 黑色
Name: xixi : Color: 红色
====================
============[]
2013-7-3 9:33:34 org.apache.cxf.services.HelloWorldImplService.HelloWorldImplPort.HelloWorld
信息: Outbound Message
---------------------------
ID: 2
Address: http://127.0.0.1:8080/helloService
Encoding: UTF-8
Content-Type: text/xml
Headers: {Accept=[*/*], SOAPAction=[""]}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header><authHeader><username>tom</username><password>123</password></authHeader></soap:Header><soap:Body><ns2:getAllCats xmlns:ns2="http://dao.ws.tdtk.cn/"/></soap:Body></soap:Envelope>
--------------------------------------
2013-7-3 9:33:34 org.apache.cxf.services.HelloWorldImplService.HelloWorldImplPort.HelloWorld
信息: Inbound Message
----------------------------
ID: 2
Response-Code: 200
Encoding: UTF-8
Content-Type: text/xml;charset=UTF-8
Headers: {Content-Length=[709], content-type=[text/xml;charset=UTF-8], Server=[Jetty(7.5.4.v20111024)]}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:getAllCatsResponse xmlns:ns2="http://dao.ws.tdtk.cn/"><return><entrys><key>第4个</key><value><color>黑色</color><id>2</id><name>huanhuan</name></value></entrys><entrys><key>第3个</key><value><color>橙色</color><id>1</id><name>机器猫</name></value></entrys><entrys><key>第5个</key><value><color>红色</color><id>3</id><name>xixi</name></value></entrys><entrys><key>第1个</key><value><color>橙色</color><id>1</id><name>lulu</name></value></entrys><entrys><key>第2个</key><value><color>黑色</color><id>2</id><name>haha</name></value></entrys></return></ns2:getAllCatsResponse></soap:Body></soap:Envelope>
--------------------------------------
第4个 : huanhuan
第3个 : 机器猫
第5个 : xixi
第1个 : lulu
第2个 : haha