XFire提供了四种身份验证的方式,分别是http验证,JSR181,Handler验证,WS-Security。
SOAP的原理告诉我们一个WS交互的流程是客户端发送请求->服务器接收请求->服务器发送数据->客户端接收数据,handler可以让我们在这四个操作中之前进行编码,所以,我们的验证进行在客户端发送请求和服务器接收请求的时候,因此,我们要写两个handler,然后把它们装配上就可以了。
Handler验证方式如下:
主要参考的实例是XFIREdemo中的BOOK
服务器的代码如下
- package org.codehaus.xfire.demo.handlers;
- import org.codehaus.xfire.MessageContext;
- import org.codehaus.xfire.XFireRuntimeException;
- import org.codehaus.xfire.handler.AbstractHandler;
- import org.jdom.Element;
- import org.jdom.Namespace;
- /**
- * @author <a href="mailto:tsztelak@gmail.com">Tomasz Sztelak</a>
- *
- * Retrive service version from SOAP header.
- */
- public class CheckVersionHandler extends AbstractHandler {
- private static final String VERSION_TAG = "version";
- private static final String VERSION_NS = "http://xfire.codehaus.org/Book";
- public void invoke(MessageContext ctx) throws Exception {
- // Check if header exists
- Element header = ctx.getInMessage().getHeader();
- if (header == null) {
- throw new XFireRuntimeException("Missing SOAP header");
- }
- // Does it have version tag
- Element version = header.getChild(VERSION_TAG, Namespace
- .getNamespace(VERSION_NS));
- if (version == null) {
- throw new XFireRuntimeException("Missing version header");
- }
- ctx.setProperty("ServiceVersion", version.getText());
- }
- }
客户端的代码
- package org.codehaus.xfire.demo.handlers;
- import org.codehaus.xfire.MessageContext;
- import org.codehaus.xfire.handler.AbstractHandler;
- import org.jdom.Element;
- /**
- * @author <a href="mailto:tsztelak@gmail.com">Tomasz Sztelak</a>
- *
- * Add version info to SOAP header.
- */
- public class OutHeaderHandler extends AbstractHandler {
- private static final String VERSION_TAG = "version";
- private static final String VERSION_NS = "http://xfire.codehaus.org/Book";
- public void invoke(MessageContext ctx) throws Exception {
- Element header = ctx.getOutMessage().getOrCreateHeader();
- header.addContent(new Element(VERSION_TAG ,VERSION_NS).addContent("1.0"));
- }
- }
然后需要在services.xml中配置如下:
xml 代码
- <!-- START SNIPPET: services -->
- <beans xmlns="http://xfire.codehaus.org/config/1.0">
- <service>
- <name>BookService</name>
- <namespace>http://xfire.codehaus.org/BookService</namespace>
- <serviceClass>org.codehaus.xfire.demo.BookService</serviceClass>
- <implementationClass>org.codehaus.xfire.demo.BookServiceImpl</implementationClass>
- <inHandlers>
- <handler handlerClass="org.codehaus.xfire.demo.handlers.CheckVersionHandler" />
- </inHandlers>
- </service>
- </beans>
- <!-- END SNIPPET: services -->