II. 参考资料
4. 共享组件
本章探讨了在客户端和服务器端 Spring-WS 开发之间共享的组件。这些接口和类代表了 Spring-WS 的构建块,因此即使你不直接使用它们,你也需要了解它们的作用。
4.1. Web 服务消息
本节描述了 Spring-WS 使用的消息和消息工厂。
4.1.1.WebServiceMessage
Spring Web 服务的核心接口之一是WebServiceMessage
.此接口表示与协议无关的 XML 消息。该接口包含一些方法,这些方法以javax.xml.transform.Source
或javax.xml.transform.Result
.Source
和Result
是标记接口,表示 XML 输入和输出的抽象。具体实现包装各种 XML 表示形式,如下表所示:
源或结果实现 | 包装的 XML 表示 |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
除了读取和写入有效负载之外,Web 服务消息还可以将自身写入输出流。
4.1.2.SoapMessage
SoapMessage
是WebServiceMessage
.它包含特定于 SOAP 的方法,例如获取 SOAP 标头、SOAP 错误等。通常,您的代码不应依赖于SoapMessage
,因为 SOAP 正文的内容(消息的有效负载)可以通过使用getPayloadSource()
和getPayloadResult()
在WebServiceMessage
.仅当需要执行特定于 SOAP 的作(例如添加标头、获取附件等)时,才需要强制转换WebServiceMessage
自SoapMessage
.
4.1.3. 消息工厂
具体消息实现由WebServiceMessageFactory
.此工厂可以创建空消息或从 input 流中读取消息。有两种具体的实现WebServiceMessageFactory
.一个基于 SAAJ,即用于 Java 的带附件的 SOAP API。另一个基于 Axis 2 的 AXIOM(AXis 对象模型)。
SaajSoapMessageFactory
这SaajSoapMessageFactory
使用带有附件的 SOAP API for Java (SAAJ) 创建SoapMessage
实现。SAAJ 是 J2EE 1.4 的一部分,因此大多数现代应用程序服务器都应该支持它。以下是常见应用程序服务器提供的 SAAJ 版本的概述:
应用服务器 | SAAJ 版本 |
---|---|
BEA WebLogic 8 |
1.1 |
BEA WebLogic 9 |
1.1/1.21 |
IBM WebSphere 6 |
1.2 |
SUN 琉璃鱼 1 |
1.3 |
1Weblogic 9 在 SAAJ 1.2 实现中有一个已知的错误:它实现了所有 1.2 接口,但抛出了一个 |
此外,Java SE 6 还包括 SAAJ 1.3。您可以将SaajSoapMessageFactory
如下:
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory" />
SAAJ 基于 DOM,即文档对象模型。这意味着所有 SOAP 消息都存储在内存中。对于较大的 SOAP 消息,这可能不是性能。在这种情况下,AxiomSoapMessageFactory 可能更适用。 |
AxiomSoapMessageFactory
这AxiomSoapMessageFactory
使用 AXis 2 对象模型 (AXIOM) 创建SoapMessage
实现。AXIOM 基于 StAX,即 XML 的流式 API。StAX 提供了一种基于拉取的机制来读取 XML 消息,这对于较大的消息可能更有效。
要提高AxiomSoapMessageFactory
中,您可以设置payloadCaching
属性设置为 false(默认值为 true)。这样做会导致直接从套接字流中读取 SOAP 主体的内容。启用此设置后,负载只能读取一次。这意味着您必须确保消息的任何预处理(日志记录或其他工作)都不会消耗它。
您可以使用AxiomSoapMessageFactory
如下:
<bean id="messageFactory" class="org.springframework.ws.soap.axiom.AxiomSoapMessageFactory">
<property name="payloadCaching" value="true"/>
</bean>
除了有效负载缓存之外,AXIOM 还支持完整的流式消息,如StreamingWebServiceMessage
.这意味着您可以直接在响应消息上设置有效负载,而不是将其写入 DOM 树或缓冲区。
当处理程序方法返回 JAXB2 支持的对象时,使用 AXIOM 的完全流式处理。它会自动将此封送对象设置为响应消息,并在响应发出时将其写入传出套接字流。
有关完全流式处理的更多信息,请参阅StreamingWebServiceMessage
和StreamingPayload
.
SOAP 1.1 或 1.2
这SaajSoapMessageFactory
和AxiomSoapMessageFactory
有一个soapVersion
属性,您可以在其中注入SoapVersion
不断。默认情况下,版本为 1.1,但您可以将其设置为 1.2:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.0.xsd">
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory">
<property name="soapVersion">
<util:constant static-field="org.springframework.ws.soap.SoapVersion.SOAP_12"/>
</property>
</bean>
</beans>
在前面的示例中,我们定义了一个SaajSoapMessageFactory
,它只接受 SOAP 1.2 消息。
尽管两个版本的 SOAP 在格式上非常相似,但 1.2 版本与 1.1 不向后兼容,因为它使用不同的 XML 命名空间。SOAP 1.1 和 1.2 之间的其他主要区别包括错误的不同结构以及 对于 SOAP 版本号(或一般的 WS-* 规范版本号)需要注意的一件重要事情是,规范的最新版本通常不是最流行的版本。对于 SOAP,这意味着(目前)最好使用的版本是 1.1。1.2 版本将来可能会变得更流行,但 1.1 是目前最安全的选择。 |
4.1.4.MessageContext
通常,消息成对出现:请求和响应。在客户端创建一个请求,该请求通过某种传输方式发送到服务器端,在那里生成响应。此响应将发送回客户端,并在客户端中读取。
在 Spring Web 服务中,这样的对话包含在MessageContext
,它具有用于获取请求和响应消息的属性。在客户端,消息上下文由WebServiceTemplate
.在服务器端,消息上下文从特定于传输的 input 流中读取。例如,在 HTTP 中,它是从HttpServletRequest
,响应将写回HttpServletResponse
.
4.2.TransportContext
SOAP 协议的一个关键属性是它试图与传输无关。这就是为什么,例如, Spring-WS 不支持通过 HTTP 请求 URL 而是通过消息内容将消息映射到端点的原因。
但是,有时需要在客户端或服务器端访问底层传输。为此,Spring Web 服务具有TransportContext
.传输上下文允许访问底层WebServiceConnection
,通常为HttpServletConnection
在服务器端或HttpUrlConnection
或CommonsHttpConnection
在客户端。例如,您可以在服务器端终端节点或拦截器中获取当前请求的 IP 地址:
TransportContext context = TransportContextHolder.getTransportContext();
HttpServletConnection connection = (HttpServletConnection )context.getConnection();
HttpServletRequest request = connection.getHttpServletRequest();
String ipAddress = request.getRemoteAddr();
4.3. 使用 XPath 处理 XML
处理 XML 的最佳方法之一是使用 XPath。引用 [effective-xml],第 35 项:
XPath 是第四代声明性语言,它允许您指定要处理的节点,而无需指定处理器应该如何导航到这些节点。XPath 的数据模型设计得非常好,可以准确地支持几乎所有开发人员都希望从 XML 中获得的内容。例如,它合并所有相邻文本(包括 CDATA 部分中的文本),允许计算跳过注释和处理指令的值,并包含来自子元素和后代元素的文本,并要求解析所有外部实体引用。在实践中,XPath 表达式往往对 Importing 文档中的意外但可能无关紧要的更改更加健壮。
Spring Web 服务有两种方法可以在应用程序中使用 XPath:更快的XPathExpression
或更灵活的XPathTemplate
.
4.3.1.XPathExpression
这XPathExpression
是对已编译的 XPath 表达式(如 Java 5javax.xml.xpath.XPathExpression
interface 或 JaxenXPath
类。要在应用程序上下文中构造表达式,可以使用XPathExpressionFactoryBean
.下面的示例使用此工厂 Bean:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="nameExpression" class="org.springframework.xml.xpath.XPathExpressionFactoryBean">
<property name="expression" value="/Contacts/Contact/Name"/>
</bean>
<bean id="myEndpoint" class="sample.MyXPathClass">
<constructor-arg ref="nameExpression"/>
</bean>
</beans>
前面的表达式不使用命名空间,但我们可以使用namespaces
工厂 Bean 的属性。该表达式可以在代码中使用,如下所示:
package sample;
public class MyXPathClass {
private final XPathExpression nameExpression;
public MyXPathClass(XPathExpression nameExpression) {
this.nameExpression = nameExpression;
}
public void doXPath(Document document) {
String name = nameExpression.evaluateAsString(document.getDocumentElement());
System.out.println("Name: " + name);
}
}
要获得更灵活的方法,您可以使用NodeMapper
,这与RowMapper
在 Spring 的 JDBC 支持中。以下示例演示如何使用它:
package sample;
public class MyXPathClass {
private final XPathExpression contactExpression;
public MyXPathClass(XPathExpression contactExpression) {
this.contactExpression = contactExpression;
}
public void doXPath(Document document) {
List contacts = contactExpression.evaluate(document,
new NodeMapper() {
public Object mapNode(Node node, int nodeNum) throws DOMException {
Element contactElement = (Element) node;
Element nameElement = (Element) contactElement.getElementsByTagName("Name").item(0);
Element phoneElement = (Element) contactElement.getElementsByTagName("Phone").item(0);
return new Contact(nameElement.getTextContent(), phoneElement.getTextContent());
}
});
PlainText Section qName; // do something with the list of Contact objects
}
}
类似于 Spring JDBC 的RowMapper
中,每个结果节点都使用匿名内部类进行映射。在本例中,我们创建一个Contact
object,我们稍后会使用它。
4.3.2.XPathTemplate
这XPathExpression
允许您仅计算单个预编译的表达式。一个更灵活但更慢的替代方案是XpathTemplate
.这个类遵循整个 Spring 中使用的通用模板模式(JdbcTemplate
,JmsTemplate
等)。下面的清单显示了一个示例:
package sample;
public class MyXPathClass {
private XPathOperations template = new Jaxp13XPathTemplate();
public void doXPath(Source source) {
String name = template.evaluateAsString("/Contacts/Contact/Name", request);
// do something with name
}
}
4.4. 消息记录和跟踪
在开发或调试 Web 服务时,在 (SOAP) 消息到达时或发送之前查看其内容可能非常有用。Spring Web 服务通过标准的 Commons Logging 接口提供此功能。
确保使用 Commons Logging 版本 1.1 或更高版本。早期版本存在类加载问题,并且不与 Log4J TRACE 级别集成。 |
要记录所有服务器端消息,请将org.springframework.ws.server.MessageTracing
logger 级别设置为DEBUG
或TRACE
.在DEBUG
级别,则仅记录 payload 根元素。在TRACE
级别,则会记录整个消息内容。如果您只想记录已发送的消息,请使用org.springframework.ws.server.MessageTracing.sent
记录。同样,您可以使用org.springframework.ws.server.MessageTracing.received
以仅记录收到的消息。
在客户端,存在类似的 Logger:org.springframework.ws.client.MessageTracing.sent
和org.springframework.ws.client.MessageTracing.received
.
以下示例log4j.properties
配置文件在客户端记录已发送消息的完整内容,并且仅记录客户端接收消息的 payload 根元素。在服务器端,将记录已发送和已接收消息的有效负载根:
log4j.rootCategory=INFO, stdout
log4j.logger.org.springframework.ws.client.MessageTracing.sent=TRACE
log4j.logger.org.springframework.ws.client.MessageTracing.received=DEBUG
log4j.logger.org.springframework.ws.server.MessageTracing=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%p [%c{3}] %m%n
使用此配置时,典型输出为:
TRACE [client.MessageTracing.sent] Sent request [<SOAP-ENV:Envelope xmlns:SOAP-ENV="... DEBUG [server.MessageTracing.received] Received request [SaajSoapMessage {http://example.com}request] ... DEBUG [server.MessageTracing.sent] Sent response [SaajSoapMessage {http://example.com}response] ... DEBUG [client.MessageTracing.received] Received response [SaajSoapMessage {http://example.com}response] ...
5. 使用 Spring-WS 创建 Web 服务
Spring-WS 的服务器端支持是围绕MessageDispatcher
通过可配置的终端节点映射、响应生成和终端节点拦截将传入消息分派到终端节点。端点通常使用@Endpoint
annotation 并具有一个或多个处理方法。这些方法通过检查消息的各个部分(通常是有效负载)来处理传入的 XML 请求消息,并创建某种响应。您可以使用另一个注释来注释该方法,通常@PayloadRoot
,以指示它可以处理的消息类型。
Spring-WS 的 XML 处理非常灵活。端点可以从 Spring-WS 支持的大量 XML 处理库中进行选择,包括:
-
DOM 系列:W3C DOM、JDOM、dom4j 和 XOM
-
SAX 或 StAX:实现更快的性能
-
XPath:从消息中提取信息
-
编组技术(JAXB、Castor、XMLBeans、JiBX 或 XStream):将 XML 转换为对象,反之亦然
5.1. 使用MessageDispatcher
Spring-WS 的服务器端是围绕一个中心类设计的,该类将传入的 XML 消息分派到端点。Spring-WS 的MessageDispatcher
非常灵活,允许你使用任何类型的类作为端点,只要它可以在 Spring IoC 容器中进行配置即可。在某种程度上,消息调度程序类似于 Spring 的DispatcherServlet
这
Spring Web MVC 中使用的 “Front Controller”。
以下序列图显示了MessageDispatcher
:

当MessageDispatcher
设置为使用,并且收到针对该特定调度程序的请求,MessageDispatcher
开始处理请求。以下过程描述了如何MessageDispatcher
处理请求:
-
配置的
EndpointMapping(s)
将搜索适当的端点。如果找到终端节点,则调用与终端节点关联的调用链(预处理器、后处理器和终端节点)以创建响应。 -
为终端节点找到合适的适配器。这
MessageDispatcher
委托此适配器来调用端点。 -
如果返回响应,则会在发送过程中发送响应。如果未返回响应(这可能是由于前处理器或后处理器拦截了请求,例如,出于安全原因),则不会发送任何响应。
在处理请求期间引发的异常将由应用程序上下文中声明的任何端点异常解析程序选取。使用这些异常解析程序可以定义自定义行为(例如返回 SOAP 错误),以防引发此类异常。
这MessageDispatcher
具有多个用于设置端点适配器、映射、异常解析程序的属性。但是,不需要设置这些属性,因为 Dispatcher 会自动检测在应用程序上下文中注册的所有类型。仅当需要覆盖检测时,才应设置这些属性。
消息调度程序在消息上下文上运行,而不是在特定于传输的输入流和输出流上运行。因此,特定于传输的请求需要读取到MessageContext
.对于 HTTP,这是通过WebServiceMessageReceiverHandlerAdapter
(这是一个 Spring WebHandlerInterceptor
),这样MessageDispatcher
可以按照标准DispatcherServlet
.但是,有一种更方便的方法可以做到这一点,如MessageDispatcherServlet
.
5.2. 传输
Spring Web 服务支持多种传输协议。最常见的是 HTTP 传输,为此提供了自定义 Servlet,但您也可以通过 JMS 甚至电子邮件发送消息。
5.2.1.MessageDispatcherServlet
这MessageDispatcherServlet
是标准Servlet
方便地从标准 Spring Web 扩展DispatcherServlet
并包装一个MessageDispatcher
.因此,它将这些属性合二为一。作为MessageDispatcher
,它遵循与上一节中描述的相同的请求处理流程。作为 Servlet,MessageDispatcherServlet
在web.xml
的 Web 应用程序。请求MessageDispatcherServlet
要处理必须由同一web.xml
文件。这是标准的 Java EE servlet 配置。以下示例显示了这样一个MessageDispatcherServlet
声明和映射:
<web-app>
<servlet>
<servlet-name>spring-ws</servlet-name>
<servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-ws</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
在前面的示例中,所有请求都由spring-ws
MessageDispatcherServlet
.这只是设置 Spring Web Services 的第一步,因为还需要配置 Spring-WS 框架使用的各种组件 bean。此配置由标准 Spring XML 组成<bean/>
定义。因为MessageDispatcherServlet
是标准 SpringDispatcherServlet
它
-servlet.xml在WEB-INF
目录中,并在 Spring 容器中创建在那里定义的 bean。在前面的示例中,它查找 '/WEB-INF/spring-ws-servlet.xml'。此文件包含所有 Spring Web Services bean,例如端点、编组器等。
作为web.xml
,如果您在 Servlet 3+ 环境中运行,则可以以编程方式配置 Spring-WS。为此,Spring-WS 提供了许多抽象基类,这些基类扩展了WebApplicationInitializer
接口。如果您还使用@Configuration
类,您应该扩展AbstractAnnotationConfigMessageDispatcherServletInitializer
:
public class MyServletInitializer
extends AbstractAnnotationConfigMessageDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{MyRootConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{MyEndpointConfig.class};
}
}
在前面的示例中,我们告诉 Spring 端点 bean 定义可以在MyEndpointConfig
类(即@Configuration
类)。其他 bean 定义(通常是 services、repositories 等)可以在MyRootConfig
类。默认情况下,AbstractAnnotationConfigMessageDispatcherServletInitializer
将 Servlet 映射到两种模式:/services
和*.wsdl
,但您可以通过覆盖getServletMappings()
方法。有关MessageDispatcherServlet
,请参阅 JavadocAbstractMessageDispatcherServletInitializer
和AbstractAnnotationConfigMessageDispatcherServletInitializer
.
自动 WSDL 公开
这MessageDispatcherServlet
自动检测任何WsdlDefinition
bean 的 bean 定义。所有WsdlDefinition
检测到的 bean 也会通过WsdlDefinitionHandlerAdapter
.这是通过定义一些 bean 向客户端公开 WSDL 的一种便捷方法。
通过一个例子,请考虑以下内容<static-wsdl>
定义,在 Spring-WS 配置文件(/WEB-INF/[servlet-name]-servlet.xml
).请注意id
属性,因为它在公开 WSDL 时使用。
<sws:static-wsdl id="orders" location="orders.wsdl"/>
或者,它可以是一个@Bean
方法中的@Configuration
类:
@Bean
public SimpleWsdl11Definition orders() {
return new SimpleWsdl11Definition(new ClassPathResource("orders.wsdl"));
}
您可以访问在orders.wsdl
文件在 Classpath 上通过GET
请求到以下形式的 URL(根据需要替换 Host、Port 和 Servlet 上下文路径):
http://localhost:8080/spring-ws/orders.wsdl
都WsdlDefinition bean 定义由MessageDispatcherServlet 在其 Bean 名称下,后缀为 '.wsdl'。因此,如果 bean 名称为echo ,则 host name 为server ,而 Servlet 上下文(war 名称)为spring-ws 中,可以在http://server/spring-ws/echo.wsdl . |
另一个不错的功能MessageDispatcherServlet
(或者更准确地说,WsdlDefinitionHandlerAdapter
) 的值,则它可以将location
它公开的所有 WSDL 中,以反映传入请求的 URL。
请注意,此location
默认情况下,转换功能处于关闭状态。要打开此功能,您需要为MessageDispatcherServlet
:
<web-app>
<servlet>
<servlet-name>spring-ws</servlet-name>
<servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
<init-param>
<param-name>transformWsdlLocations</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>spring-ws</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
如果您使用AbstractAnnotationConfigMessageDispatcherServletInitializer
启用转换就像覆盖isTransformWsdlLocations()
method 返回true
.
请查阅WsdlDefinitionHandlerAdapter
类以了解有关整个转换过程的更多信息。
作为手动编写 WSDL 并使用<static-wsdl>
,Spring Web 服务还可以从 XSD 模式生成 WSDL。这是发布 WSDL 中所示的方法。下一个应用程序上下文代码段展示了如何创建这样的动态 WSDL 文件:
<sws:dynamic-wsdl id="orders"
portTypeName="Orders"
locationUri="http://localhost:8080/ordersService/">
<sws:xsd location="Orders.xsd"/>
</sws:dynamic-wsdl>
或者,您可以使用 Java@Bean
方法:
@Bean
public DefaultWsdl11Definition orders() {
DefaultWsdl11Definition definition = new DefaultWsdl11Definition();
definition.setPortTypeName("Orders");
definition.setLocationUri("http://localhost:8080/ordersService/");
definition.setSchema(new SimpleXsdSchema(new ClassPathResource("echo.xsd")));
return definition;
}
这<dynamic-wsdl>
元素依赖于DefaultWsdl11Definition
类。此定义类在org.springframework.ws.wsdl.wsdl11.provider
package 和ProviderBasedWsdl4jDefinition
类来生成 WSDL。请参阅这些类的类级 Javadoc,了解如何在必要时扩展此机制。
这DefaultWsdl11Definition
(因此,<dynamic-wsdl>
标记中)使用约定从 XSD 架构构建 WSDL。它迭代所有element
元素,并创建一个message
for all elements 的接下来,它创建一个 WSDLoperation
对于以 defined request 或 response 后缀结尾的所有消息。默认请求后缀为Request
.默认响应后缀为Response
,但可以通过设置requestSuffix
和responseSuffix
attributes 开启<dynamic-wsdl />
分别。它还构建了一个portType
,binding
和service
基于作。
例如,如果Orders.xsd
schema 定义GetOrdersRequest
和GetOrdersResponse
元素<dynamic-wsdl>
创建一个GetOrdersRequest
和GetOrdersResponse
message 和GetOrders
作,该作被放入Orders
端口类型。
要使用多个模式,无论是通过包含还是导入,您都可以将 Commons XMLSchema 放在类路径上。如果 Commons XMLSchema 位于类路径上,则<dynamic-wsdl>
元素遵循所有 XSD 导入,并将它们作为单个 XSD 包含在 WSDL 中并内联。这大大简化了架构的部署,同时仍允许单独编辑它们。
尽管在运行时从 XSD 创建 WSDL 很方便,但这种方法有几个缺点。首先,尽管我们试图在版本之间保持 WSDL 生成过程的一致性,但它仍然有可能发生变化(略有变化)。其次,生成速度有点慢,但是,一旦生成,WSDL 就会被缓存以供以后参考。 |
因此,您应该使用<dynamic-wsdl>
仅在项目的开发阶段。我们建议使用浏览器下载生成的 WSDL,将其存储在项目中,并使用<static-wsdl>
.这是真正确保 WSDL 不会随时间变化的唯一方法。
5.2.2. 在DispatcherServlet
作为MessageDispatcherServlet
,您可以将MessageDispatcher
在标准的 Spring-Web MVC 中DispatcherServlet
.默认情况下,DispatcherServlet
can delegate only to (只能委托给Controllers
,但我们可以指示它委托给MessageDispatcher
通过添加WebServiceMessageReceiverHandlerAdapter
添加到 servlet 的 Web 应用程序上下文中:
<beans>
<bean class="org.springframework.ws.transport.http.WebServiceMessageReceiverHandlerAdapter"/>
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="defaultHandler" ref="messageDispatcher"/>
</bean
<bean id="messageDispatcher" class="org.springframework.ws.soap.server.SoapMessageDispatcher"/>
...
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
</beans>
请注意,通过显式添加WebServiceMessageReceiverHandlerAdapter
,则调度程序 Servlet 不会加载默认适配器,并且无法处理标准 Spring-MVC@Controllers
.因此,我们添加了RequestMappingHandlerAdapter
在结尾。
以类似的方式,您可以将WsdlDefinitionHandlerAdapter
要确保DispatcherServlet
可以处理WsdlDefinition
接口:
<beans>
<bean class="org.springframework.ws.transport.http.WebServiceMessageReceiverHandlerAdapter"/>
<bean class="org.springframework.ws.transport.http.WsdlDefinitionHandlerAdapter"/>
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="*.wsdl">myServiceDefinition</prop>
</props>
</property>
<property name="defaultHandler" ref="messageDispatcher"/>
</bean>
<bean id="messageDispatcher" class="org.springframework.ws.soap.server.SoapMessageDispatcher"/>
<bean id="myServiceDefinition" class="org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition">
<prop name="wsdl" value="/WEB-INF/myServiceDefintion.wsdl"/>
</bean>
...
</beans>
5.2.3. JMS 传输
Spring Web 服务通过 Spring 框架中提供的 JMS 功能支持服务器端 JMS 处理。Spring Web 服务提供了WebServiceMessageListener
以插入MessageListenerContainer
.此消息侦听器需要一个WebServiceMessageFactory
和MessageDispatcher
进行作。下面的配置示例显示了这一点:
<beans>
<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="vm://localhost?broker.persistent=false"/>
</bean>
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"/>
<bean class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="destinationName" value="RequestQueue"/>
<property name="messageListener">
<bean class="org.springframework.ws.transport.jms.WebServiceMessageListener">
<property name="messageFactory" ref="messageFactory"/>
<property name="messageReceiver" ref="messageDispatcher"/>
</bean>
</property>
</bean>
<bean id="messageDispatcher" class="org.springframework.ws.soap.server.SoapMessageDispatcher">
<property name="endpointMappings">
<bean
class="org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping">
<property name="defaultEndpoint">
<bean class="com.example.MyEndpoint"/>
</property>
</bean>
</property>
</bean>
</beans>
5.2.4. 电子邮件传输
除了 HTTP 和 JMS 之外, Spring Web 服务还提供服务器端电子邮件处理。此功能通过MailMessageReceiver
类。此类监视 POP3 或 IMAP 文件夹,将电子邮件转换为WebServiceMessage
,并使用 SMTP 发送任何响应。您可以通过storeUri
,它指示要监控请求的邮件文件夹(通常是 POP3 或 IMAP 文件夹),以及transportUri
,它指示用于发送响应的服务器(通常是 SMTP 服务器)。
您可以配置MailMessageReceiver
使用可插拔策略监控传入消息:MonitoringStrategy
.默认情况下,使用轮询策略,其中每 5 分钟轮询一次传入文件夹以获取新邮件。您可以通过设置pollingInterval
策略上的属性。默认情况下,所有MonitoringStrategy
implementations 删除已处理的消息。您可以通过设置deleteMessages
财产。
作为效率相当低的轮询方法的替代方法,有一种使用 IMAP IDLE 的监视策略。IDLE 命令是 IMAP 电子邮件协议的可选扩展,它允许邮件服务器将新的邮件更新发送到MailMessageReceiver
异步。如果使用支持 IDLE 命令的 IMAP 服务器,则可以将ImapIdleMonitoringStrategy
到monitoringStrategy
财产。除了支持服务器之外,您还需要使用 JavaMail 版本 1.4.1 或更高版本。
以下配置显示了如何使用服务器端电子邮件支持,覆盖默认轮询间隔以每 30 秒(30.000 毫秒)检查一次:
<beans>
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"/>
<bean id="messagingReceiver" class="org.springframework.ws.transport.mail.MailMessageReceiver">
<property name="messageFactory" ref="messageFactory"/>
<property name="from" value="Spring-WS SOAP Server <[email protected]>"/>
<property name="storeUri" value="imap://server:[email protected]/INBOX"/>
<property name="transportUri" value="smtp://smtp.example.com"/>
<property name="messageReceiver" ref="messageDispatcher"/>
<property name="monitoringStrategy">
<bean class="org.springframework.ws.transport.mail.monitor.PollingMonitoringStrategy">
<property name="pollingInterval" value="30000"/>
</bean>
</property>
</bean>
<bean id="messageDispatcher" class="org.springframework.ws.soap.server.SoapMessageDispatcher">
<property name="endpointMappings">
<bean
class="org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping">
<property name="defaultEndpoint">
<bean class="com.example.MyEndpoint"/>
</property>
</bean>
</property>
</bean>
</beans>
5.2.5. 嵌入式 HTTP 服务器传输
Spring Web 服务提供了一种基于 Sun 的 JRE 1.6 HTTP 服务器的传输。嵌入式 HTTP Server 是一个易于配置的独立服务器。它为传统的 servlet 容器提供了一种更轻量级的替代方案。
使用嵌入式 HTTP 服务器时,不需要外部部署描述符 (web.xml
).您只需定义服务器的实例并将其配置为处理传入请求。核心 Spring 框架中的 remoting 模块包含一个用于 HTTP 服务器的便捷工厂 Bean:SimpleHttpServerFactoryBean
.最重要的属性是contexts
,它将上下文路径映射到相应的HttpHandler
实例。
Spring Web 服务提供了HttpHandler
接口:WsdlDefinitionHttpHandler
和WebServiceMessageReceiverHttpHandler
.前者将传入的 GET 请求映射到WsdlDefinition
.后者负责处理 Web 服务消息的 POST 请求,因此需要一个WebServiceMessageFactory
(通常为SaajSoapMessageFactory
) 和WebServiceMessageReceiver
(通常SoapMessageDispatcher
) 完成其任务。
为了与 servlet 世界进行比较,contexts
property 在web.xml
和WebServiceMessageReceiverHttpHandler
等价于MessageDispatcherServlet
.
以下代码段显示了 HTTP 服务器传输的配置示例:
<beans>
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"/>
<bean id="messageReceiver" class="org.springframework.ws.soap.server.SoapMessageDispatcher">
<property name="endpointMappings" ref="endpointMapping"/>
</bean>
<bean id="endpointMapping" class="org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping">
<property name="defaultEndpoint" ref="stockEndpoint"/>
</bean>
<bean id="httpServer" class="org.springframework.remoting.support.SimpleHttpServerFactoryBean">
<property name="contexts">
<map>
<entry key="/StockService.wsdl" value-ref="wsdlHandler"/>
<entry key="/StockService" value-ref="soapHandler"/>
</map>
</property>
</bean>
<bean id="soapHandler" class="org.springframework.ws.transport.http.WebServiceMessageReceiverHttpHandler">
<property name="messageFactory" ref="messageFactory"/>
<property name="messageReceiver" ref="messageReceiver"/>
</bean>
<bean id="wsdlHandler" class="org.springframework.ws.transport.http.WsdlDefinitionHttpHandler">
<property name="definition" ref="wsdlDefinition"/>
</bean>
</beans>
有关SimpleHttpServerFactoryBean
,请参阅 Javadoc。
5.2.6. XMPP 传输
Spring Web Services 2.0 引入了对 XMPP(也称为 Jabber)的支持。该支持基于 Smack 库。
Spring Web 服务对 XMPP 的支持与其他传输非常相似:有一个XmppMessageSender
对于WebServiceTemplate
以及XmppMessageReceiver
与MessageDispatcher
.
以下示例显示如何设置服务器端 XMPP 组件:
<beans>
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"/>
<bean id="connection" class="org.springframework.ws.transport.xmpp.support.XmppConnectionFactoryBean">
<property name="host" value="jabber.org"/>
<property name="username" value="username"/>
<property name="password" value="password"/>
</bean>
<bean id="messagingReceiver" class="org.springframework.ws.transport.xmpp.XmppMessageReceiver">
<property name="messageFactory" ref="messageFactory"/>
<property name="connection" ref="connection"/>
<property name="messageReceiver" ref="messageDispatcher"/>
</bean>
<bean id="messageDispatcher" class="org.springframework.ws.soap.server.SoapMessageDispatcher">
<property name="endpointMappings">
<bean
class="org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping">
<property name="defaultEndpoint">
<bean class="com.example.MyEndpoint"/>
</property>
</bean>
</property>
</bean>
</beans>
5.3. 终端节点
端点是 Spring-WS 服务器端支持的核心概念。终端节点提供对应用程序行为的访问,该行为通常由业务服务接口定义。终端节点解释 XML 请求消息,并使用该输入(通常)调用业务服务上的方法。该服务调用的结果表示为响应消息。Spring-WS 具有各种各样的端点,并使用各种方式来处理 XML 消息和创建响应。
您可以通过使用@Endpoint
注解。在该类中,通过使用各种参数类型(比如 DOM 元素、JAXB2 对象等),定义一个或多个处理传入 XML 请求的方法。您可以使用另一个注释(通常@PayloadRoot
).
请考虑以下示例终端节点:
package samples;
@Endpoint (1)
public class AnnotationOrderEndpoint {
private final OrderService orderService;
@Autowired (2)
public AnnotationOrderEndpoint(OrderService orderService) {
this.orderService = orderService;
}
@PayloadRoot(localPart = "order", namespace = "http://samples") (5)
public void order(@RequestPayload Element orderElement) { (3)
Order order = createOrder(orderElement);
orderService.createOrder(order);
}
@PayloadRoot(localPart = "orderRequest", namespace = "http://samples") (5)
@ResponsePayload
public Order getOrder(@RequestPayload OrderRequest orderRequest, SoapHeader header) { (4)
checkSoapHeaderForSomething(header);
return orderService.getOrder(orderRequest.getId());
}
...
}
1
The class is annotated with @Endpoint
, marking it as a Spring-WS endpoint.
2
The constructor is marked with @Autowired
so that the OrderService
business service is injected into this endpoint.
3
The order
method takes an Element
(annotated with @RequestPayload
) as a parameter. This means that the payload of the message is passed on this method as a DOM element. The method has a void
return type, indicating that no response message is sent.
For more information about endpoint methods, see @Endpoint
handling methods.
4
The getOrder
method takes an OrderRequest
(also annotated with @RequestPayload
) as a parameter. This parameter is a JAXB2-supported object (it is annotated with @XmlRootElement
). This means that the payload of the message is passed to this method as a unmarshalled object. The SoapHeader
type is also given as a parameter. On invocation, this parameter contains the SOAP header of the request message. The method is also annotated with @ResponsePayload
, indicating that the return value (the Order
) is used as the payload of the response message.
For more information about endpoint methods, see @Endpoint
handling methods.
5
The two handling methods of this endpoint are marked with @PayloadRoot
, indicating what sort of request messages can be handled by the method: the getOrder
method is invoked for requests with a orderRequest
local name and a http://samples
namespace URI. The order method is invoked for requests with a order
local name.
For more information about @PayloadRoot
, see Endpoint mappings.
To enable the support for @Endpoint
and related Spring-WS annotations, you need to add the following to your Spring application context:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:sws="http://www.springframework.org/schema/web-services"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/web-services
http://www.springframework.org/schema/web-services/web-services.xsd">
*<sws:annotation-driven />
</beans>
Alternatively, if you use @Configuration
classes instead of Spring XML, you can annotate your configuration class with @EnableWs
:
@EnableWs
@Configuration
public class EchoConfig {
// @Bean definitions go here
}
To customize the @EnableWs
configuration, you can implement WsConfigurer
or, better yet, extend the WsConfigurerAdapter
:
@Configuration
@EnableWs
@ComponentScan(basePackageClasses = { MyConfiguration.class })
public class MyConfiguration extends WsConfigurerAdapter {
@Override
public void addInterceptors(List<EndpointInterceptor> interceptors) {
interceptors.add(new MyInterceptor());
}
@Override
public void addArgumentResolvers(List<MethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new MyArgumentResolver());
}
// More overridden methods ...
}
In the next couple of sections, a more elaborate description of the @Endpoint
programming model is given.
Endpoints, like any other Spring Bean, are scoped as a singleton by default. That is, one instance of the bean definition is created per container. Being a singleton implies that more than one thread can use it at the same time, so the endpoint has to be thread safe. If you want to use a different scope, such as prototype, see the Spring Reference documentation.
Note that all abstract base classes provided in Spring-WS are thread safe, unless otherwise indicated in the class-level Javadoc.
5.3.1. @Endpoint
handling methods
For an endpoint to actually handle incoming XML messages, it needs to have one or more handling methods. Handling methods can take wide range of parameters and return types. However, they typically have one parameter that contains the message payload, and they return the payload of the response message (if any). This section covers which parameter and return types are supported.
To indicate what sort of messages a method can handle, the method is typically annotated with either the @PayloadRoot
or the @SoapAction
annotation. You can learn more about these annotations in Endpoint mappings.
The following example shows a handling method:
@PayloadRoot(localPart = "order", namespace = "http://samples")
public void order(@RequestPayload Element orderElement) {
Order order = createOrder(orderElement);
orderService.createOrder(order);
}
The order
method takes an Element
(annotated with @RequestPayload
) as a parameter. This means that the payload of the message is passed on this method as a DOM element. The method has a void
return type, indicating that no response message is sent.
Handling Method Parameters
The handling method typically has one or more parameters that refer to various parts of the incoming XML message. Most commonly, the handling method has a single parameter that maps to the payload of the message, but it can also map to other parts of the request message, such as a SOAP header. This section describes the parameters you can use in your handling method signatures.
To map a parameter to the payload of the request message, you need to annotate this parameter with the @RequestPayload
annotation. This annotation tells Spring-WS that the parameter needs to be bound to the request payload.
The following table describes the supported parameter types. It shows the supported types, whether the parameter should be annotated with @RequestPayload
, and any additional notes.
Name
Supported parameter types
@RequestPayload
required?
Additional notes
TrAX
javax.xml.transform.Source
and sub-interfaces (DOMSource
, SAXSource
, StreamSource
, and StAXSource
)
Yes
Enabled by default.
W3C DOM
org.w3c.dom.Element
Yes
Enabled by default
dom4j
org.dom4j.Element
Yes
Enabled when dom4j is on the classpath.
JDOM
org.jdom.Element
Yes
Enabled when JDOM is on the classpath.
XOM
nu.xom.Element
Yes
Enabled when XOM is on the classpath.
StAX
javax.xml.stream.XMLStreamReader
and javax.xml.stream.XMLEventReader
Yes
Enabled when StAX is on the classpath.
XPath
Any boolean, double, String
, org.w3c.Node
, org.w3c.dom.NodeList
, or type that can be converted from a String
by a Spring conversion service, and that is annotated with @XPathParam
.
No
Enabled by default, see the section called XPathParam
.
Message context
org.springframework.ws.context.MessageContext
No
Enabled by default.
SOAP
org.springframework.ws.soap.SoapMessage
, org.springframework.ws.soap.SoapBody
, org.springframework.ws.soap.SoapEnvelope
, org.springframework.ws.soap.SoapHeader
, and org.springframework.ws.soap.SoapHeaderElement`s when used in combination with the `@SoapHeader
annotation.
No
Enabled by default.
JAXB2
Any type that is annotated with javax.xml.bind.annotation.XmlRootElement
, and javax.xml.bind.JAXBElement
.
Yes
Enabled when JAXB2 is on the classpath.
OXM
Any type supported by a Spring OXM Unmarshaller
.
Yes
Enabled when the unmarshaller
attribute of <sws:annotation-driven/>
is specified.
The next few examples show possible method signatures. The following method is invoked with the payload of the request message as a DOM org.w3c.dom.Element
:
public void handle(@RequestPayload Element element)
The following method is invoked with the payload of the request message as a javax.xml.transform.dom.DOMSource
. The header
parameter is bound to the SOAP header of the request message.
public void handle(@RequestPayload DOMSource domSource, SoapHeader header)
The following method is invoked with the payload of the request message unmarshalled into a MyJaxb2Object
(which is annotated with @XmlRootElement
). The payload of the message is also given as a DOM Element
. The whole message context is passed on as the third parameter.
public void handle(@RequestPayload MyJaxb2Object requestObject, @RequestPayload Element element, Message messageContext)
As you can see, there are a lot of possibilities when it comes to defining how to handle method signatures. You can even extend this mechanism to support your own parameter types. See the Javadoc of DefaultMethodEndpointAdapter
and MethodArgumentResolver
to see how.
@XPathParam
One parameter type needs some extra explanation: @XPathParam
. The idea here is that you annotate one or more method parameters with an XPath expression and that each such annotated parameter is bound to the evaluation of the expression. The following example shows how to do so:
package samples;
@Endpoint
public class AnnotationOrderEndpoint {
private final OrderService orderService;
public AnnotationOrderEndpoint(OrderService orderService) {
this.orderService = orderService;
}
@PayloadRoot(localPart = "orderRequest", namespace = "http://samples")
@Namespace(prefix = "s", uri="http://samples")
public Order getOrder(@XPathParam("/s:orderRequest/@id") int orderId) {
Order order = orderService.getOrder(orderId);
// create Source from order and return it
}
}
Since we use the s
prefix in our XPath expression, we must bind it to the http://samples
namespace. This is accomplished with the @Namespace
annotation. Alternatively, we could have placed this annotation on the type-level to use the same namespace mapping for all handler methods or even the package-level (in package-info.java
) to use it for multiple endpoints.
By using the @XPathParam
, you can bind to all the data types supported by XPath:
-
boolean
or Boolean
-
double
or Double
-
String
-
Node
-
NodeList
In addition to this list, you can use any type that can be converted from a String
by a Spring conversion service.
Handling method return types
To send a response message, the handling needs to specify a return type. If no response message is required, the method can declare a void
return type. Most commonly, the return type is used to create the payload of the response message. However, you can also map to other parts of the response message. This section describes the return types you can use in your handling method signatures.
To map the return value to the payload of the response message, you need to annotate the method with the @ResponsePayload
annotation. This annotation tells Spring-WS that the return value needs to be bound to the response payload.
The following table describes the supported return types. It shows the supported types, whether the parameter should be annotated with @ResponsePayload
, and any additional notes.
Name
Supported return types
@ResponsePayload
required?
Additional notes
No response
void
No
Enabled by default.
TrAX
javax.xml.transform.Source
and sub-interfaces (DOMSource
, SAXSource
, StreamSource
, and StAXSource
)
Yes
Enabled by default.
W3C DOM
org.w3c.dom.Element
Yes
Enabled by default
dom4j
org.dom4j.Element
Yes
Enabled when dom4j is on the classpath.
JDOM
org.jdom.Element
Yes
Enabled when JDOM is on the classpath.
XOM
nu.xom.Element
Yes
Enabled when XOM is on the classpath.
JAXB2
Any type that is annotated with javax.xml.bind.annotation.XmlRootElement
, and javax.xml.bind.JAXBElement
.
Yes
Enabled when JAXB2 is on the classpath.
OXM
Any type supported by a Spring OXM Marshaller
.
Yes
Enabled when the marshaller
attribute of <sws:annotation-driven/>
is specified.
There are a lot of possibilities when it comes to defining handling method signatures. It is even possible to extend this mechanism to support your own parameter types. See the class-level Javadoc of DefaultMethodEndpointAdapter
and MethodReturnValueHandler
to see how.
5.4. Endpoint mappings
The endpoint mapping is responsible for mapping incoming messages to appropriate endpoints. Some endpoint mappings are enabled by default — for example, the PayloadRootAnnotationMethodEndpointMapping
or the SoapActionAnnotationMethodEndpointMapping
. However, we first need to examine the general concept of an EndpointMapping
.
An EndpointMapping
delivers a EndpointInvocationChain
, which contains the endpoint that matches the incoming request and may also contain a list of endpoint interceptors that are applied to the request and response. When a request comes in, the MessageDispatcher
hands it over to the endpoint mapping to let it inspect the request and come up with an appropriate EndpointInvocationChain
. Then the MessageDispatcher
invokes the endpoint and any interceptors in the chain.
The concept of configurable endpoint mappings that can optionally contain interceptors (which can, in turn, manipulate the request, the response, or both) is extremely powerful. A lot of supporting functionality can be built into custom EndpointMapping
implementations. For example, a custom endpoint mapping could choose an endpoint based not only on the contents of a message but also on a specific SOAP header (or, indeed, multiple SOAP headers).
Most endpoint mappings inherit from the AbstractEndpointMapping
, which offers an ‘interceptors’ property, which is the list of interceptors to use. EndpointInterceptors
are discussed in Intercepting Requests — the EndpointInterceptor
Interface. Additionally, there is the defaultEndpoint
, which is the default endpoint to use when this endpoint mapping does not result in a matching endpoint.
As explained in Endpoints, the @Endpoint
style lets you handle multiple requests in one endpoint class. This is the responsibility of the MethodEndpointMapping
. This mapping determines which method is to be invoked for an incoming request message.
There are two endpoint mappings that can direct requests to methods: the PayloadRootAnnotationMethodEndpointMapping
and the SoapActionAnnotationMethodEndpointMapping
You can enable both methods by using <sws:annotation-driven/>
in your application context.
The PayloadRootAnnotationMethodEndpointMapping
uses the @PayloadRoot
annotation, with the localPart
and namespace
elements, to mark methods with a particular qualified name. Whenever a message comes in with this qualified name for the payload root element, the method is invoked. For an example, see above.
Alternatively, the SoapActionAnnotationMethodEndpointMapping
uses the @SoapAction
annotation to mark methods with a particular SOAP Action. Whenever a message comes in with this SOAPAction
header, the method is invoked.
5.4.1. WS-Addressing
WS-Addressing specifies a transport-neutral routing mechanism. It is based on the To
and Action
SOAP headers, which indicate the destination and intent of the SOAP message, respectively. Additionally, WS-Addressing lets you define a return address (for normal messages and for faults) and a unique message identifier, which can be used for correlation. For more information on WS-Addressing, see https://en.wikipedia.org/wiki/WS-Addressing. The following example shows a WS-Addressing message:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope"
xmlns:wsa="http://www.w3.org/2005/08/addressing">
<SOAP-ENV::Header>
<wsa:MessageID>urn:uuid:21363e0d-2645-4eb7-8afd-2f5ee1bb25cf</wsa:MessageID>
<wsa:ReplyTo>
<wsa:Address>http://example.com/business/client1</wsa:Address>
</wsa:ReplyTo>
<wsa:To S:mustUnderstand="true">http://example/com/fabrikam</wsa:To>
<wsa:Action>http://example.com/fabrikam/mail/Delete</wsa:Action>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<f:Delete xmlns:f="http://example.com/fabrikam">
<f:maxCount>42</f:maxCount>
</f:Delete>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
In the preceding example, the destination is set to http://example/com/fabrikam
, while the action is set to http://example.com/fabrikam/mail/Delete
. Additionally, there is a message identifier and a reply-to address. By default, this address is the “anonymous” address, indicating that a response should be sent byusing the same channel as the request (that is, the HTTP response), but it can also be another address, as indicated in this example.
In Spring Web Services, WS-Addressing is implemented as an endpoint mapping. By using this mapping, you associate WS-Addressing actions with endpoints, similar to the SoapActionAnnotationMethodEndpointMapping
described earlier.
Using AnnotationActionEndpointMapping
The AnnotationActionEndpointMapping
is similar to the SoapActionAnnotationMethodEndpointMapping
but uses WS-Addressing headers instead of the SOAP Action transport header.
To use the AnnotationActionEndpointMapping
, annotate the handling methods with the @Action
annotation, similar to the @PayloadRoot
and @SoapAction
annotations described in @Endpoint
handling methods and Endpoint mappings. The following example shows how to do so:
package samples;
@Endpoint
public class AnnotationOrderEndpoint {
private final OrderService orderService;
public AnnotationOrderEndpoint(OrderService orderService) {
this.orderService = orderService;
}
@Action("http://samples/RequestOrder")
public Order getOrder(OrderRequest orderRequest) {
return orderService.getOrder(orderRequest.getId());
}
@Action("http://samples/CreateOrder")
public void order(Order order) {
orderService.createOrder(order);
}
}
The preceding mapping routes requests that have a WS-Addressing Action
of http://samples/RequestOrder
to the getOrder
method. Requests with http://samples/CreateOrder
are routed to the order
method..
By default, the AnnotationActionEndpointMapping
supports both the 1.0 (May 2006), and the August 2004 editions of WS-Addressing. These two versions are most popular and are interoperable with Axis 1 and 2, JAX-WS, XFire, Windows Communication Foundation (WCF), and Windows Services Enhancements (WSE) 3.0. If necessary, specific versions of the spec can be injected into the versions
property.
In addition to the @Action
annotation, you can annotate the class with the @Address
annotation. If set, the value is compared to the To
header property of the incoming message.
Finally, there is the messageSenders
property, which is required for sending response messages to non-anonymous, out-of-bound addresses. You can set MessageSender
implementations in this property, the same as you would on the WebServiceTemplate
. See URIs and Transports.
5.4.2. Intercepting Requests — the EndpointInterceptor
Interface
The endpoint mapping mechanism has the notion of endpoint interceptors. These can be extremely useful when you want to apply specific functionality to certain requests — for example, dealing with security-related SOAP headers or the logging of request and response message.
Endpoint interceptors are typically defined by using a <sws:interceptors>
element in your application context. In this element, you can define endpoint interceptor beans that apply to all endpoints defined in that application context. Alternatively, you can use <sws:payloadRoot>
or <sws:soapAction>
elements to specify for which payload root name or SOAP action the interceptor should apply. The following example shows how to do so:
<sws:interceptors>
<bean class="samples.MyGlobalInterceptor"/>
<sws:payloadRoot namespaceUri="http://www.example.com">
<bean class="samples.MyPayloadRootInterceptor"/>
</sws:payloadRoot>
<sws:soapAction value="http://www.example.com/SoapAction">
<bean class="samples.MySoapActionInterceptor1"/>
<ref bean="mySoapActionInterceptor2"/>
</sws:soapAction>
</sws:interceptors>
<bean id="mySoapActionInterceptor2" class="samples.MySoapActionInterceptor2"/>
In the preceding example, we define one “global” interceptor (MyGlobalInterceptor
) that intercepts all requests and responses. We also define an interceptor that applies only to XML messages that have the http://www.example.com
as a payload root namespace. We could have defined a localPart
attribute in addition to the namespaceUri
to further limit the messages the to which interceptor applies. Finally, we define two interceptors that apply when the message has a http://www.example.com/SoapAction
SOAP action. Notice how the second interceptor is actually a reference to a bean definition outside of the <interceptors>
element. You can use bean references anywhere inside the <interceptors>
element.
When you use @Configuration
classes, you can extend from WsConfigurerAdapter
to add interceptors:
@Configuration
@EnableWs
public class MyWsConfiguration extends WsConfigurerAdapter {
@Override
public void addInterceptors(List<EndpointInterceptor> interceptors) {
interceptors.add(new MyPayloadRootInterceptor());
}
}
Interceptors must implement the EndpointInterceptor
interface from the org.springframework.ws.server
package. This interface defines three methods, one that can be used for handling the request message before the actual endpoint is processed, one that can be used for handling a normal response message, and one that can be used for handling fault messages. The second two are called after the endpoint is processed. These three methods should provide enough flexibility to do all kinds of pre- and post-processing.
The handleRequest(..)
method on the interceptor returns a boolean value. You can use this method to interrupt or continue the processing of the invocation chain. When this method returns true
, the endpoint processing chain will continue. When it returns false
, the MessageDispatcher
interprets this to mean that the interceptor itself has taken care of things and does not continue processing the other interceptors and the actual endpoint in the invocation chain. The handleResponse(..)
and handleFault(..)
methods also have a boolean return value. When these methods return false
, the response will not be sent back to the client.
There are a number of standard EndpointInterceptor
implementations that you can use in your Web service. Additionally, there is the XwsSecurityInterceptor
, which is described in XwsSecurityInterceptor
.
PayloadLoggingInterceptor
and SoapEnvelopeLoggingInterceptor
When developing a web service, it can be useful to log the incoming and outgoing XML messages. Spring WS facilitates this with the PayloadLoggingInterceptor
and SoapEnvelopeLoggingInterceptor
classes. The former logs only the payload of the message to the Commons Logging Log. The latter logs the entire SOAP envelope, including SOAP headers. The following example shows how to define the PayloadLoggingInterceptor
in an endpoint mapping:
<sws:interceptors>
<bean class="org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor"/>
</sws:interceptors>
Both of these interceptors have two properties, logRequest
and logResponse
, which can be set to false
to disable logging for either request or response messages.
You could use the WsConfigurerAdapter
approach, as described earlier, for the PayloadLoggingInterceptor
as well.
PayloadValidatingInterceptor
One of the benefits of using a contract-first development style is that we can use the schema to validate incoming and outgoing XML messages. Spring-WS facilitates this with the PayloadValidatingInterceptor
. This interceptor requires a reference to one or more W3C XML or RELAX NG schemas and can be set to validate requests, responses, or both.
Note that request validation may sound like a good idea, but it makes the resulting Web service very strict. Usually, it is not really important whether the request validates, only if the endpoint can get sufficient information to fulfill a request. Validating the response is a good idea, because the endpoint should adhere to its schema. Remember Postel’s Law:
"Be conservative in what you do; be liberal in what you accept from others."
The following example uses the PayloadValidatingInterceptor
. In this example, we use the schema in /WEB-INF/orders.xsd
to validate the response but not the request. Note that the PayloadValidatingInterceptor
can also accept multiple schemas by setting the schemas
property.
<bean id="validatingInterceptor"
class="org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor">
<property name="schema" value="/WEB-INF/orders.xsd"/>
<property name="validateRequest" value="false"/>
<property name="validateResponse" value="true"/>
</bean>
Of course, you could use the WsConfigurerAdapter
approach, as described earlier, for the PayloadValidatingInterceptor
as well.
Using PayloadTransformingInterceptor
To transform the payload to another XML format, Spring Web Services offers the PayloadTransformingInterceptor
. This endpoint interceptor is based on XSLT style sheets and is especially useful when supporting multiple versions of a web service, because you can transform the older message format to the newer format. The following example uses the PayloadTransformingInterceptor
:
<bean id="transformingInterceptor"
class="org.springframework.ws.server.endpoint.interceptor.PayloadTransformingInterceptor">
<property name="requestXslt" value="/WEB-INF/oldRequests.xslt"/>
<property name="responseXslt" value="/WEB-INF/oldResponses.xslt"/>
</bean>
In the preceding example, we transform requests by using /WEB-INF/oldRequests.xslt
and response messages by using /WEB-INF/oldResponses.xslt
. Note that, since endpoint interceptors are registered at the endpoint-mapping level, you can create an endpoint mapping that applies to the “old style” messages and add the interceptor to that mapping. Hence, the transformation applies only to these “old style” message.
You could use the WsConfigurerAdapter
approach, as described earlier, for the PayloadTransformingInterceptor
as well.
5.5. Handling Exceptions
Spring-WS provides EndpointExceptionResolvers
to ease the pain of unexpected exceptions occurring while your message is being processed by an endpoint that matched the request. Endpoint exception resolvers somewhat resemble the exception mappings that can be defined in the web application descriptor web.xml
. However, they provide a more flexible way to handle exceptions. They provide information about what endpoint was invoked when the exception was thrown. Furthermore, a programmatic way of handling exceptions gives you many more options for how to respond appropriately. Rather than expose the innards of your application by giving an exception and stack trace, you can handle the exception any way you want — for example, by returning a SOAP fault with a specific fault code and string.
Endpoint exception resolvers are automatically picked up by the MessageDispatcher
, so no explicit configuration is necessary.
Besides implementing the EndpointExceptionResolver
interface, which is only a matter of implementing the resolveException(MessageContext, endpoint, Exception)
method, you may also use one of the provided implementations. The simplest implementation is the SimpleSoapExceptionResolver
, which creates a SOAP 1.1 Server or SOAP 1.2 Receiver fault and uses the exception message as the fault string. The SimpleSoapExceptionResolver
is the default, but it can be overridden by explicitly adding another resolver.
5.5.1. SoapFaultMappingExceptionResolver
The SoapFaultMappingExceptionResolver
is a more sophisticated implementation. This resolver lets you take the class name of any exception that might be thrown and map it to a SOAP Fault:
<beans>
<bean id="exceptionResolver"
class="org.springframework.ws.soap.server.endpoint.SoapFaultMappingExceptionResolver">
<property name="defaultFault" value="SERVER"/>
<property name="exceptionMappings">
<value>
org.springframework.oxm.ValidationFailureException=CLIENT,Invalid request
</value>
</property>
</bean>
</beans>
The key values and default endpoint use a format of faultCode,faultString,locale
, where only the fault code is required. If the fault string is not set, it defaults to the exception message. If the language is not set, it defaults to English. The preceding configuration maps exceptions of type ValidationFailureException
to a client-side SOAP fault with a fault string of Invalid request
, as follows:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Client</faultcode>
<faultstring>Invalid request</faultstring>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
If any other exception occurs, it returns the default fault: a server-side fault with the exception message as the fault string.
5.5.2. Using SoapFaultAnnotationExceptionResolver
You can also annotate exception classes with the @SoapFault
annotation, to indicate the SOAP fault that should be returned whenever that exception is thrown. For these annotations to be picked up, you need to add the SoapFaultAnnotationExceptionResolver
to your application context. The elements of the annotation include a fault code enumeration, fault string or reason, and language. The following example shows such an exception:
package samples;
@SoapFault(faultCode = FaultCode.SERVER)
public class MyBusinessException extends Exception {
public MyClientException(String message) {
super(message);
}
}
Whenever the MyBusinessException
is thrown with the constructor string "Oops!"
during endpoint invocation, it results in the following response:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Server</faultcode>
<faultstring>Oops!</faultstring>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
5.6. Server-side Testing
When it comes to testing your Web service endpoints, you have two possible approaches:
-
Write Unit Tests, where you provide (mock) arguments for your endpoint to consume.
The advantage of this approach is that it is quite easy to accomplish (especially for classes annotated with @Endpoint
). The disadvantage is that you are not really testing the exact content of the XML messages that are sent over the wire.
-
Write Integrations Tests, which do test the contents of the message.
The first approach can easily be accomplished with mocking frameworks such as EasyMock, JMock, and others. The next section focuses on writing integration tests, using the test features introduced in Spring Web Services 2.0.
5.6.1. Writing server-side integration tests
Spring Web Services 2.0 introduced support for creating endpoint integration tests. In this context, an endpoint is a class that handles (SOAP) messages (see Endpoints).
The integration test support lives in the org.springframework.ws.test.server
package. The core class in that package is the MockWebServiceClient
. The underlying idea is that this client creates a request message and then sends it over to the endpoints that are configured in a standard MessageDispatcherServlet
application context (see MessageDispatcherServlet
). These endpoints handle the message and create a response. The client then receives this response and verifies it against registered expectations.
The typical usage of the MockWebServiceClient
is: .
-
Create a MockWebServiceClient
instance by calling MockWebServiceClient.createClient(ApplicationContext)
or MockWebServiceClient.createClient(WebServiceMessageReceiver, WebServiceMessageFactory)
.
-
Send request messages by calling sendRequest(RequestCreator)
, possibly by using the default RequestCreator
implementations provided in RequestCreators
(which can be statically imported).
-
Set up response expectations by calling andExpect(ResponseMatcher)
, possibly by using the default ResponseMatcher
implementations provided in ResponseMatchers
(which can be statically imported). Multiple expectations can be set up by chaining andExpect(ResponseMatcher)
calls.
Note that the MockWebServiceClient
(and related classes) offers a “fluent” API, so you can typically use the code-completion features in your IDE to guide you through the process of setting up the mock server.
Also note that you can rely on the standard logging features available in Spring Web Services in your unit tests. Sometimes, it might be useful to inspect the request or response message to find out why a particular tests failed. See Message Logging and Tracing for more information.
Consider, for example, the following web service endpoint class:
@Endpoint (1)
public class CustomerEndpoint {
@ResponsePayload (2)
public CustomerCountResponse getCustomerCount( (2)
@RequestPayload CustomerCountRequest request) { (2)
CustomerCountResponse response = new CustomerCountResponse();
response.setCustomerCount(10);
return response;
}
}
1
The CustomerEndpoint
in annotated with @Endpoint
. See Endpoints.
2
The getCustomerCount()
method takes a CustomerCountRequest
as its argument and returns a CustomerCountResponse
. Both of these classes are objects supported by a marshaller. For instance, they can have a @XmlRootElement
annotation to be supported by JAXB2.
The following example shows a typical test for CustomerEndpoint
:
@RunWith(SpringJUnit4ClassRunner.class) (2)
@ContextConfiguration("spring-ws-servlet.xml") (2)
public class CustomerEndpointIntegrationTest {
@Autowired
private ApplicationContext applicationContext; (3)
private MockWebServiceClient mockClient;
@Before
public void createClient() {
mockClient = MockWebServiceClient.createClient(applicationContext); (4)
}
@Test
public void customerEndpoint() throws Exception {
Source requestPayload = new StringSource(
"<customerCountRequest xmlns='http://springframework.org/spring-ws'>" +
"<customerName>John Doe</customerName>" +
"</customerCountRequest>");
Source responsePayload = new StringSource(
"<customerCountResponse xmlns='http://springframework.org/spring-ws'>" +
"<customerCount>10</customerCount>" +
"</customerCountResponse>");
mockClient.sendRequest(withPayload(requestPayload)). (5)
andExpect(payload(responsePayload)); (5)
}
}
1
The CustomerEndpointIntegrationTest
imports the MockWebServiceClient
and statically imports RequestCreators
and ResponseMatchers
.
2
This test uses the standard testing facilities provided in the Spring Framework. This is not required but is generally the easiest way to set up the test.
3
The application context is a standard Spring-WS application context (see MessageDispatcherServlet
), read from spring-ws-servlet.xml
. In this case, the application context contains a bean definition for CustomerEndpoint
(or perhaps a <context:component-scan />
is used).
4
In a @Before
method, we create a MockWebServiceClient
by using the createClient
factory method.
5
We send a request by calling sendRequest()
with a withPayload()
RequestCreator
provided by the statically imported RequestCreators
(see Using RequestCreator
and RequestCreators
).
We also set up response expectations by calling andExpect()
with a payload()
ResponseMatcher
provided by the statically imported ResponseMatchers
(see Using ResponseMatcher
and ResponseMatchers
).
This part of the test might look a bit confusing, but the code completion features of your IDE are of great help. After typing sendRequest(
, your IDE can provide you with a list of possible request creating strategies, provided you statically imported RequestCreators
. The same applies to andExpect()
, provided you statically imported ResponseMatchers
.
5.6.2. Using RequestCreator
and RequestCreators
Initially, the MockWebServiceClient
needs to create a request message for the endpoint to consume. The client uses the RequestCreator
strategy interface for this purpose:
public interface RequestCreator {
WebServiceMessage createRequest(WebServiceMessageFactory messageFactory)
throws IOException;
}
You can write your own implementations of this interface, creating a request message by using the message factory, but you certainly do not have to. The RequestCreators
class provides a way to create a RequestCreator
based on a given payload in the withPayload()
method. You typically statically import RequestCreators
.
5.6.3. Using ResponseMatcher
and ResponseMatchers
When the request message has been processed by the endpoint and a response has been received, the MockWebServiceClient
can verify whether this response message meets certain expectations. The client uses the ResponseMatcher
strategy interface for this purpose:
public interface ResponseMatcher {
void match(WebServiceMessage request,
WebServiceMessage response)
throws IOException, AssertionError;
}
Once again, you can write your own implementations of this interface, throwing AssertionError
instances when the message does not meet your expectations, but you certainly do not have to, as the ResponseMatchers
class provides standard ResponseMatcher
implementations for you to use in your tests. You typically statically import this class.
The ResponseMatchers
class provides the following response matchers:
ResponseMatchers
method
Description
payload()
Expects a given response payload.
validPayload()
Expects the response payload to validate against given XSD schemas.
xpath()
Expects a given XPath expression to exist, not exist, or evaluate to a given value.
soapHeader()
Expects a given SOAP header to exist in the response message.
noFault()
Expects that the response message does not contain a SOAP Fault.
mustUnderstandFault()
, clientOrSenderFault()
, serverOrReceiverFault()
, and versionMismatchFault()
Expects the response message to contain a specific SOAP Fault.
You can set up multiple response expectations by chaining andExpect()
calls:
mockClient.sendRequest(...).
andExpect(payload(expectedResponsePayload)).
andExpect(validPayload(schemaResource));
For more information on the response matchers provided by ResponseMatchers
, see the Javadoc.
6. Using Spring Web Services on the Client
Spring-WS provides a client-side Web service API that allows for consistent, XML-driven access to web services. It also caters to the use of marshallers and unmarshallers so that your service-tier code can deal exclusively with Java objects.
The org.springframework.ws.client.core
package provides the core functionality for using the client-side access API. It contains template classes that simplify the use of Web services, much like the core Spring JdbcTemplate
does for JDBC. The design principle common to Spring template classes is to provide helper methods to perform common operations and, for more sophisticated usage, delegate to user implemented callback interfaces. The web service template follows the same design. The classes offer various convenience methods for
-
Sending and receiving of XML messages
-
Marshalling objects to XML before sending
-
Allowing for multiple transport options
6.1. Using the Client-side API
This section describs how to use the client-side API. For how to use the server-side API, see Creating a Web service with Spring-WS.
6.1.1. WebServiceTemplate
The WebServiceTemplate
is the core class for client-side web service access in Spring-WS. It contains methods for sending Source
objects and receiving response messages as either Source
or Result
. Additionally, it can marshal objects to XML before sending them across a transport and unmarshal any response XML into an object again.
URIs and Transports
The WebServiceTemplate
class uses an URI as the message destination. You can either set a defaultUri
property on the template itself or explicitly supply a URI when calling a method on the template. The URI is resolved into a WebServiceMessageSender
, which is responsible for sending the XML message across a transport layer. You can set one or more message senders by using the messageSender
or messageSenders
properties of the WebServiceTemplate
class.
HTTP transports
There are two implementations of the WebServiceMessageSender
interface for sending messages over HTTP. The default implementation is the HttpUrlConnectionMessageSender
, which uses the facilities provided by Java itself. The alternative is the HttpComponentsMessageSender
, which uses the Apache HttpComponents HttpClient. Use the latter if you need more advanced and easy-to-use functionality (such as authentication, HTTP connection pooling, and so forth).
To use the HTTP transport, either set the defaultUri
to something like http://example.com/services
or supply the uri
parameter for one of the methods.
The following example shows how to use default configuration for HTTP transports:
<beans>
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"/>
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory"/>
<property name="defaultUri" value="http://example.com/WebService"/>
</bean>
</beans>
The following example shows how to override the default configuration and how to use Apache HttpClient to authenticate with HTTP authentication:
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory"/>
<property name="messageSender">
<bean class="org.springframework.ws.transport.http.HttpComponentsMessageSender">
<property name="credentials">
<bean class="org.apache.http.auth.UsernamePasswordCredentials">
<constructor-arg value="john:secret"/>
</bean>
</property>
</bean>
</property>
<property name="defaultUri" value="http://example.com/WebService"/>
</bean>
JMS transport
For sending messages over JMS, Spring Web Services provides JmsMessageSender
. This class uses the facilities of the Spring framework to transform the WebServiceMessage
into a JMS Message
, send it on its way on a Queue
or Topic
, and receive a response (if any).
To use JmsMessageSender
, you need to set the defaultUri
or uri
parameter to a JMS URI, which — at a minimum — consists of the jms:
prefix and a destination name. Some examples of JMS URIs are: jms:SomeQueue
, jms:SomeTopic?priority=3&deliveryMode=NON_PERSISTENT
, and jms:RequestQueue?replyToName=ResponseName
. For more information on this URI syntax, see the Javadoc for JmsMessageSender
.
By default, the JmsMessageSender
sends JMS BytesMessage
, but you can override this to use TextMessages
by using the messageType
parameter on the JMS URI — for example, jms:Queue?messageType=TEXT_MESSAGE
. Note that BytesMessages
are the preferred type, because TextMessages
do not support attachments and character encodings reliably.
The following example shows how to use the JMS transport in combination with an ActiveMQ connection factory:
<beans>
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"/>
<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="vm://localhost?broker.persistent=false"/>
</bean>
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory"/>
<property name="messageSender">
<bean class="org.springframework.ws.transport.jms.JmsMessageSender">
<property name="connectionFactory" ref="connectionFactory"/>
</bean>
</property>
<property name="defaultUri" value="jms:RequestQueue?deliveryMode=NON_PERSISTENT"/>
</bean>
</beans>
Email Transport
Spring Web Services also provides an email transport, which you can use to send web service messages over SMTP and retrieve them over either POP3 or IMAP. The client-side email functionality is contained in the MailMessageSender
class. This class creates an email message from the request WebServiceMessage
and sends it over SMTP. It then waits for a response message to arrive at the incoming POP3 or IMAP server.
To use the MailMessageSender
, set the defaultUri
or uri
parameter to a mailto
URI — for example, mailto:[email protected]
or mailto:server@localhost?subject=SOAP%20Test
. Make sure that the message sender is properly configured with a transportUri
, which indicates the server to use for sending requests (typically a SMTP server), and a storeUri
, which indicates the server to poll for responses (typically a POP3 or IMAP server).
The following example shows how to use the email transport:
<beans>
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"/>
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory"/>
<property name="messageSender">
<bean class="org.springframework.ws.transport.mail.MailMessageSender">
<property name="from" value="Spring-WS SOAP Client <[email protected]>"/>
<property name="transportUri" value="smtp://client:[email protected]"/>
<property name="storeUri" value="imap://client:[email protected]/INBOX"/>
</bean>
</property>
<property name="defaultUri" value="mailto:[email protected]?subject=SOAP%20Test"/>
</bean>
</beans>
XMPP Transport
Spring Web Services 2.0 introduced an XMPP (Jabber) transport, which you can use to send and receive web service messages over XMPP. The client-side XMPP functionality is contained in the XmppMessageSender
class. This class creates an XMPP message from the request WebServiceMessage
and sends it over XMPP. It then listens for a response message to arrive.
To use the XmppMessageSender
, set the defaultUri
or uri
parameter to a xmpp
URI — for example, xmpp:[email protected]
. The sender also requires an XMPPConnection
to work, which can be conveniently created by using the org.springframework.ws.transport.xmpp.support.XmppConnectionFactoryBean
.
The following example shows how to use the XMPP transport:
<beans>
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"/>
<bean id="connection" class="org.springframework.ws.transport.xmpp.support.XmppConnectionFactoryBean">
<property name="host" value="jabber.org"/>
<property name="username" value="username"/>
<property name="password" value="password"/>
</bean>
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory"/>
<property name="messageSender">
<bean class="org.springframework.ws.transport.xmpp.XmppMessageSender">
<property name="connection" ref="connection"/>
</bean>
</property>
<property name="defaultUri" value="xmpp:[email protected]"/>
</bean>
</beans>
Message factories
In addition to a message sender, the WebServiceTemplate
requires a web service message factory. There are two message factories for SOAP: SaajSoapMessageFactory
and AxiomSoapMessageFactory
. If no message factory is specified (by setting the messageFactory
property), Spring-WS uses the SaajSoapMessageFactory
by default.
6.1.2. Sending and Receiving a WebServiceMessage
The WebServiceTemplate
contains many convenience methods to send and receive web service messages. There are methods that accept and return a Source
and those that return a Result
. Additionally, there are methods that marshal and unmarshal objects to XML. The following example sends a simple XML message to a web service:
public class WebServiceClient {
private static final String MESSAGE =
"<message xmlns=\"http://tempuri.org\">Hello, Web Service World</message>";
private final WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
public void setDefaultUri(String defaultUri) {
webServiceTemplate.setDefaultUri(defaultUri);
}
// send to the configured default URI
public void simpleSendAndReceive() {
StreamSource source = new StreamSource(new StringReader(MESSAGE));
StreamResult result = new StreamResult(System.out);
webServiceTemplate.sendSourceAndReceiveToResult(source, result);
}
// send to an explicit URI
public void customSendAndReceive() {
StreamSource source = new StreamSource(new StringReader(MESSAGE));
StreamResult result = new StreamResult(System.out);
webServiceTemplate.sendSourceAndReceiveToResult("http://localhost:8080/AnotherWebService",
source, result);
}
}
<beans xmlns="http://www.springframework.org/schema/beans">
<bean id="webServiceClient" class="WebServiceClient">
<property name="defaultUri" value="http://localhost:8080/WebService"/>
</bean>
</beans>
The preceding example uses the WebServiceTemplate
to send a “Hello, World” message to the web service located at http://localhost:8080/WebService
(in the case of the simpleSendAndReceive()
method) and writes the result to the console. The WebServiceTemplate
is injected with the default URI, which is used because no URI was supplied explicitly in the Java code.
Note that the WebServiceTemplate
class is thread-safe once configured (assuming that all of its dependencies are also thread-safe, which is the case for all of the dependencies that ship with Spring-WS), so multiple objects can use the same shared WebServiceTemplate
instance. The WebServiceTemplate
exposes a zero-argument constructor and messageFactory
and messageSender
bean properties that you can use to construct the instance (by using a Spring container or plain Java code). Alternatively, consider deriving from Spring-WS’s WebServiceGatewaySupport
convenience base class, which exposes convenient bean properties to enable easy configuration. (You do not have to extend this base class. It is provided as a convenience class only.)
6.1.3. Sending and Receiving POJOs — Marshalling and Unmarshalling
To facilitate the sending of plain Java objects, the WebServiceTemplate
has a number of send(..)
methods that take an Object
as an argument for a message’s data content. The method marshalSendAndReceive(..)
in the WebServiceTemplate
class delegates the conversion of the request object to XML to a Marshaller
and the conversion of the response XML to an object to an Unmarshaller
. (For more information about marshalling and unmarshaller, see the Spring Framework reference documentation.) By using the marshallers, your application code can focus on the business object that is being sent or received and not be concerned with the details of how it is represented as XML. To use the marshalling functionality, you have to set a marshaller and an unmarshaller with the marshaller
and unmarshaller
properties of the WebServiceTemplate
class.
6.1.4. Using WebServiceMessageCallback
To accommodate setting SOAP headers and other settings on the message, the WebServiceMessageCallback
interface gives you access to the message after it has been created but before it is sent. The following example demonstrates how to set the SOAP action header on a message that is created by marshalling an object:
public void marshalWithSoapActionHeader(MyObject o) {
webServiceTemplate.marshalSendAndReceive(o, new WebServiceMessageCallback() {
public void doWithMessage(WebServiceMessage message) {
((SoapMessage)message).setSoapAction("http://tempuri.org/Action");
}
});
}
Note that you can also use the org.springframework.ws.soap.client.core.SoapActionCallback
to set the SOAP action header.
WS-Addressing
In addition to the server-side WS-Addressing support, Spring Web Services also has support for this specification on the client-side.
For setting WS-Addressing headers on the client, you can use org.springframework.ws.soap.addressing.client.ActionCallback
. This callback takes the desired action header as a parameter. It also has constructors for specifying the WS-Addressing version and a To
header. If not specified, the To
header defaults to the URL of the connection being made.
The following example sets the Action
header to http://samples/RequestOrder
:
webServiceTemplate.marshalSendAndReceive(o, new ActionCallback("http://samples/RequestOrder"));
6.1.5. Using WebServiceMessageExtractor
The WebServiceMessageExtractor
interface is a low-level callback interface that you have full control over the process to extract an Object
from a received WebServiceMessage
. The WebServiceTemplate
invokes the extractData(..)
method on a supplied WebServiceMessageExtractor
while the underlying connection to the serving resource is still open. The following example shows the WebServiceMessageExtractor
in action:
public void marshalWithSoapActionHeader(final Source s) {
final Transformer transformer = transformerFactory.newTransformer();
webServiceTemplate.sendAndReceive(new WebServiceMessageCallback() {
public void doWithMessage(WebServiceMessage message) {
transformer.transform(s, message.getPayloadResult());
},
new WebServiceMessageExtractor() {
public Object extractData(WebServiceMessage message) throws IOException {
// do your own transforms with message.getPayloadResult()
// or message.getPayloadSource()
}
}
});
}
6.2. Client-side Testing
When it comes to testing your Web service clients (that is, classes that use the WebServiceTemplate
to access a Web service), you have two possible approaches:
-
Write unit tests, which mock away the WebServiceTemplate
class, WebServiceOperations
interface, or the complete client class.
The advantage of this approach is that it s easy to accomplish. The disadvantage is that you are not really testing the exact content of the XML messages that are sent over the wire, especially when mocking out the entire client class.
-
Write integrations tests, which do test the contents of the message.
The first approach can easily be accomplished with mocking frameworks, such as EasyMock, JMock, and others. The next section focuses on writing integration tests, using the test features introduced in Spring Web Services 2.0.
6.2.1. Writing Client-side Integration Tests
Spring Web Services 2.0 introduced support for creating Web service client integration tests. In this context, a client is a class that uses the WebServiceTemplate
to access a web service.
The integration test support lives in the org.springframework.ws.test.client
package. The core class in that package is the MockWebServiceServer
. The underlying idea is that the web service template connects to this mock server and sends it a request message, which the mock server then verifies against the registered expectations. If the expectations are met, the mock server then prepares a response message, which is sent back to the template.
The typical usage of the MockWebServiceServer
is: .
-
Create a MockWebServiceServer
instance by calling MockWebServiceServer.createServer(WebServiceTemplate)
, MockWebServiceServer.createServer(WebServiceGatewaySupport)
, or MockWebServiceServer.createServer(ApplicationContext)
.
-
Set up request expectations by calling expect(RequestMatcher)
, possibly by using the default RequestMatcher
implementations provided in RequestMatchers
(which can be statically imported). Multiple expectations can be set up by chaining andExpect(RequestMatcher)
calls.
-
Create an appropriate response message by calling andRespond(ResponseCreator)
, possibly by using the default ResponseCreator
implementations provided in ResponseCreators
(which can be statically imported).
-
Use the WebServiceTemplate
as normal, either directly of through client code.
-
Call MockWebServiceServer.verify()
to make sure that all expectations have been met.
Note that the MockWebServiceServer
(and related classes) offers a 'fluent' API, so you can typically use the code-completion features in your IDE to guide you through the process of setting up the mock server.
Also note that you can rely on the standard logging features available in Spring Web Services in your unit tests. Sometimes, it might be useful to inspect the request or response message to find out why a particular tests failed. See Message Logging and Tracing for more information.
Consider, for example, the following Web service client class:
public class CustomerClient extends WebServiceGatewaySupport { (1)
public int getCustomerCount() {
CustomerCountRequest request = new CustomerCountRequest(); (2)
request.setCustomerName("John Doe");
CustomerCountResponse response =
(CustomerCountResponse) getWebServiceTemplate().marshalSendAndReceive(request); (3)
return response.getCustomerCount();
}
}
1
The CustomerClient
extends WebServiceGatewaySupport
, which provides it with a webServiceTemplate
property.
2
CustomerCountRequest
is an object supported by a marshaller. For instance, it can have an @XmlRootElement
annotation to be supported by JAXB2.
3
The CustomerClient
uses the WebServiceTemplate
offered by WebServiceGatewaySupport
to marshal the request object into a SOAP message and sends that to the web service. The response object is unmarshalled into a CustomerCountResponse
.
The following example shows a typical test for CustomerClient
:
@RunWith(SpringJUnit4ClassRunner.class) (2)
@ContextConfiguration("integration-test.xml") (2)
public class CustomerClientIntegrationTest {
@Autowired
private CustomerClient client; (3)
private MockWebServiceServer mockServer; (4)
@Before
public void createServer() throws Exception {
mockServer = MockWebServiceServer.createServer(client);
}
@Test
public void customerClient() throws Exception {
Source requestPayload = new StringSource(
"<customerCountRequest xmlns='http://springframework.org/spring-ws'>" +
"<customerName>John Doe</customerName>" +
"</customerCountRequest>");
Source responsePayload = new StringSource(
"<customerCountResponse xmlns='http://springframework.org/spring-ws'>" +
"<customerCount>10</customerCount>" +
"</customerCountResponse>");
mockServer.expect(payload(requestPayload)).andRespond(withPayload(responsePayload));(5)
int result = client.getCustomerCount(); (6)
assertEquals(10, result); (6)
mockServer.verify(); (7)
}
}
1
The CustomerClientIntegrationTest
imports the MockWebServiceServer
and statically imports RequestMatchers
and ResponseCreators
.
2
This test uses the standard testing facilities provided in the Spring Framework. This is not required but is generally the easiest way to set up the test.
3
The CustomerClient
is configured in integration-test.xml
and wired into this test using @Autowired
.
4
In a @Before
method, we create a MockWebServiceServer
by using the createServer
factory method.
5
We define expectations by calling expect()
with a payload()
RequestMatcher
provided by the statically imported RequestMatchers
(see Using RequestMatcher
and RequestMatchers
).
We also set up a response by calling andRespond()
with a withPayload()
ResponseCreator
provided by the statically imported ResponseCreators
(see Using ResponseCreator
and ResponseCreators
).
This part of the test might look a bit confusing, but the code-completion features of your IDE are of great help. After you type expect(
, your IDE can provide you with a list of possible request matching strategies, provided you statically imported RequestMatchers
. The same applies to andRespond(
, provided you statically imported ResponseCreators
.
6
We call getCustomerCount()
on the CustomerClient
, thus using the WebServiceTemplate
. The template has been set up for “testing mode” by now, so no real (HTTP) connection is made by this method call. We also make some JUnit assertions based on the result of the method call.
7
We call verify()
on the MockWebServiceServer
, verifying that the expected message was actually received.
6.2.2. Using RequestMatcher
and RequestMatchers
To verify whether the request message meets certain expectations, the MockWebServiceServer
uses the RequestMatcher
strategy interface. The contract defined by this interface is as follows:
public interface RequestMatcher {
void match(URI uri,
WebServiceMessage request)
throws IOException,
AssertionError;
}
You can write your own implementations of this interface, throwing AssertionError
exceptions when the message does not meet your expectations, but you certainly do not have to. The RequestMatchers
class provides standard RequestMatcher
implementations for you to use in your tests. You typically statically import this class.
The RequestMatchers
class provides the following request matchers:
RequestMatchers
method
Description
anything()
Expects any sort of request.
payload()
Expects a given request payload.
validPayload()
Expects the request payload to validate against given XSD schemas.
xpath()
Expects a given XPath expression to exist, not exist, or evaluate to a given value.
soapHeader()
Expects a given SOAP header to exist in the request message.
connectionTo()
Expects a connection to the given URL.
You can set up multiple request expectations by chaining andExpect()
calls:
mockServer.expect(connectionTo("http://example.com")).
andExpect(payload(expectedRequestPayload)).
andExpect(validPayload(schemaResource)).
andRespond(...);
For more information on the request matchers provided by RequestMatchers
, see the Javadoc.
6.2.3. Using ResponseCreator
and ResponseCreators
When the request message has been verified and meets the defined expectations, the MockWebServiceServer
creates a response message for the WebServiceTemplate
to consume. The server uses the ResponseCreator
strategy interface for this purpose:
public interface ResponseCreator {
WebServiceMessage createResponse(URI uri,
WebServiceMessage request,
WebServiceMessageFactory messageFactory)
throws IOException;
}
Once again, you can write your own implementations of this interface, creating a response message by using the message factory, but you certainly do not have to, as the ResponseCreators
class provides standard ResponseCreator
implementations for you to use in your tests. You typically statically import this class.
The ResponseCreators
class provides the following responses:
ResponseCreators
method
Description
withPayload()
Creates a response message with a given payload.
withError()
Creates an error in the response connection. This method gives you the opportunity to test your error handling.
withException()
Throws an exception when reading from the response connection. This method gives you the opportunity to test your exception handling.
withMustUnderstandFault()
, withClientOrSenderFault()
, withServerOrReceiverFault()
, or withVersionMismatchFault()
Creates a response message with a given SOAP fault. This method gives you the opportunity to test your Fault handling.
For more information on the request matchers provided by RequestMatchers
, see the Javadoc.
7. Securing Your Web services with Spring-WS
This chapter explains how to add WS-Security aspects to your Web services. We focus on the three different areas of WS-Security:
-
Authentication: This is the process of determining whether a principal is who they claim to be. In this context, a “principal” generally means a user, device or some other system that can perform an action in your application.
-
Digital signatures: The digital signature of a message is a piece of information based on both the document and the signer’s private key. It is created through the use of a hash function and a private signing function (encrypting with the signer’s private key).
-
Encryption and Decryption: Encryption is the process of transforming data into a form that is impossible to read without the appropriate key. It is mainly used to keep information hidden from anyone for whom it is not intended. Decryption is the reverse of encryption. It is the process of transforming encrypted data back into an readable form.
These three areas are implemented by using the XwsSecurityInterceptor
or Wss4jSecurityInterceptor
, which we describe in XwsSecurityInterceptor
and Using Wss4jSecurityInterceptor
, respectively
Note that WS-Security (especially encryption and signing) requires substantial amounts of memory and can decrease performance. If performance is important to you, you might want to consider not using WS-Security or using HTTP-based security.
7.1. XwsSecurityInterceptor
The XwsSecurityInterceptor
is an EndpointInterceptor
(see Intercepting Requests — the EndpointInterceptor
Interface) that is based on SUN’s XML and Web Services Security package (XWSS). This WS-Security implementation is part of the Java Web Services Developer Pack (Java WSDP).
Like any other endpoint interceptor, it is defined in the endpoint mapping (see Endpoint mappings). This means that you can be selective about adding WS-Security support. Some endpoint mappings require it, while others do not.
Note that XWSS requires both a SUN 1.5 JDK and the SUN SAAJ reference implementation. The WSS4J interceptor does not have these requirements (see Using Wss4jSecurityInterceptor
).
The XwsSecurityInterceptor
requires a security policy file to operate. This XML file tells the interceptor what security aspects to require from incoming SOAP messages and what aspects to add to outgoing messages. The basic format of the policy file is explained in the following sections, but you can find a more in-depth tutorial here. You can set the policy with the policyConfiguration
property, which requires a Spring resource. The policy file can contain multiple elements — for example, require a username token on incoming messages and sign all outgoing messages. It contains a SecurityConfiguration
element (not a JAXRPCSecurity
element) as its root.
Additionally, the security interceptor requires one or more CallbackHandler
instances to operate. These handlers are used to retrieve certificates, private keys, validate user credentials, and so on. Spring-WS offers handlers for most common security concerns — for example, authenticating against a Spring Security authentication manager and signing outgoing messages based on a X509 certificate. The following sections indicate what callback handler to use for which security concern. You can set the callback handlers by using the callbackHandler
or callbackHandlers
property.
The following example that shows how to wire up the XwsSecurityInterceptor
:
<beans>
<bean id="wsSecurityInterceptor"
class="org.springframework.ws.soap.security.xwss.XwsSecurityInterceptor">
<property name="policyConfiguration" value="classpath:securityPolicy.xml"/>
<property name="callbackHandlers">
<list>
<ref bean="certificateHandler"/>
<ref bean="authenticationHandler"/>
</list>
</property>
</bean>
...
</beans>
This interceptor is configured by using the securityPolicy.xml
file on the classpath. It uses two callback handlers that are defined later in the file.
7.1.1. Keystores
For most cryptographic operations, you an use the standard java.security.KeyStore
objects. These operations include certificate verification, message signing, signature verification, and encryption. They exclude username and time-stamp verification. This section aims to give you some background knowledge on keystores and the Java tools that you can use to store keys and certificates in a keystore file. This information is mostly not related to Spring-WS but to the general cryptographic features of Java.
The java.security.KeyStore
class represents a storage facility for cryptographic keys and certificates. It can contain three different sort of elements:
-
Private Keys: These keys are used for self-authentication. The private key is accompanied by a certificate chain for the corresponding public key. Within the field of WS-Security, this accounts for message signing and message decryption.
-
Symmetric Keys: Symmetric (or secret) keys are also used for message encryption and decryption — the difference being that both sides (sender and recipient) share the same secret key.
-
Trusted certificates: These X509 certificates are called a “trusted certificate” because the keystore owner trusts that the public key in the certificates does indeed belong to the owner of the certificate. Within WS-Security, these certificates are used for certificate validation, signature verification, and encryption.
Using keytool
The keytool
program, a key and certificate management utility, is supplied with your Java Virtual Machine. You can use this tool to create new keystores, add new private keys and certificates to them, and so on. It is beyond the scope of this document to provide a full reference of the keytool
command, but you can find a reference here or by using the keytool -help
command on the command line.
Using KeyStoreFactoryBean
To easily load a keystore by using Spring configuration, you can use the KeyStoreFactoryBean
. It has a resource location property, which you can set to point to the path of the keystore to load. A password may be given to check the integrity of the keystore data. If a password is not given, integrity checking is not performed. The following listing configures a KeyStoreFactoryBean
:
<bean id="keyStore" class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="password" value="password"/>
<property name="location" value="classpath:org/springframework/ws/soap/security/xwss/test-keystore.jks"/>
</bean>
If you do not specify the location property, a new, empty keystore is created, which is most likely not what you want.
KeyStoreCallbackHandler
To use the keystores within a XwsSecurityInterceptor
, you need to define a KeyStoreCallbackHandler
. This callback has three properties with type keystore
: (keyStore
,trustStore
, and symmetricStore
). The exact stores used by the handler depend on the cryptographic operations that are to be performed by this handler. For private key operation, the keyStore
is used. For symmetric key operations, the symmetricStore
is used. For determining trust relationships, the trustStore
is used. The following table indicates this:
Cryptographic operation
Keystore used
Certificate validation
First keyStore
, then trustStore
Decryption based on private key
keyStore
Decryption based on symmetric key
symmetricStore
Encryption based on public key certificate
trustStore
Encryption based on symmetric key
symmetricStore
Signing
keyStore
Signature verification
trustStore
Additionally, the KeyStoreCallbackHandler
has a privateKeyPassword
property, which should be set to unlock the private keys contained in the`keyStore`.
If the symmetricStore
is not set, it defaults to the keyStore
. If the key or trust store is not set, the callback handler uses the standard Java mechanism to load or create it. See the JavaDoc of the KeyStoreCallbackHandler
to know how this mechanism works.
For instance, if you want to use the KeyStoreCallbackHandler
to validate incoming certificates or signatures, you can use a trust store:
<beans>
<bean id="keyStoreHandler" class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallbackHandler">
<property name="trustStore" ref="trustStore"/>
</bean>
<bean id="trustStore" class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="location" value="classpath:truststore.jks"/>
<property name="password" value="changeit"/>
</bean>
</beans>
If you want to use it to decrypt incoming certificates or sign outgoing messages, you can use a key store:
<beans>
<bean id="keyStoreHandler" class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallbackHandler">
<property name="keyStore" ref="keyStore"/>
<property name="privateKeyPassword" value="changeit"/>
</bean>
<bean id="keyStore" class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="location" value="classpath:keystore.jks"/>
<property name="password" value="changeit"/>
</bean>
</beans>
The following sections indicate where the KeyStoreCallbackHandler
can be used and which properties to set for particular cryptographic operations.
7.1.2. Authentication
As stated in the introduction to this chapter, authentication is the task of determining whether a principal is who they claim to be. Within WS-Security, authentication can take two forms: using a username and password token (using either a plain text password or a password digest) or using a X509 certificate.
Plain Text Username Authentication
The simplest form of username authentication uses plain text passwords. In this scenario, the SOAP message contains a UsernameToken
element, which itself contains a Username
element and a Password
element which contains the plain text password. Plain text authentication can be compared to the basic authentication provided by HTTP servers.
Note that plain text passwords are not very secure. Therefore, you should always add additional security measures to your transport layer if you use them (using HTTPS instead of plain HTTP, for instance).
To require that every incoming message contains a UsernameToken
with a plain text password, the security policy file should contain a RequireUsernameToken
element, with the passwordDigestRequired
attribute set to false
. You can find a reference of possible child elements here. The following listing shows how to include a RequireUsernameToken
element:
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
...
<xwss:RequireUsernameToken passwordDigestRequired="false" nonceRequired="false"/>
...
</xwss:SecurityConfiguration>
If the username token is not present, the XwsSecurityInterceptor
returns a SOAP fault to the sender. If it is present, it fires a PasswordValidationCallback
with a PlainTextPasswordRequest
to the registered handlers. Within Spring-WS, there are three classes that handle this particular callback.
Using SimplePasswordValidationCallbackHandler
The simplest password validation handler is the SimplePasswordValidationCallbackHandler
. This handler validates passwords against an in-memory Properties
object, which you can specify byusing the users
property:
<bean id="passwordValidationHandler"
class="org.springframework.ws.soap.security.xwss.callback.SimplePasswordValidationCallbackHandler">
<property name="users">
<props>
<prop key="Bert">Ernie</prop>
</props>
</property>
</bean>
In this case, we are allowing only the user, "Bert", to log in by using the password, "Ernie".
Using SpringPlainTextPasswordValidationCallbackHandler
The SpringPlainTextPasswordValidationCallbackHandler
uses Spring Security to authenticate users. It is beyond the scope of this document to describe Spring Security, but it is a full-fledged security framework. You can read more about it in the Spring Security reference documentation.
The SpringPlainTextPasswordValidationCallbackHandler
requires an AuthenticationManager
to operate. It uses this manager to authenticate against a UsernamePasswordAuthenticationToken
that it creates. If authentication is successful, the token is stored in the SecurityContextHolder
. You can set the authentication manager by using the authenticationManager
property:
<beans>
<bean id="springSecurityHandler"
class="org.springframework.ws.soap.security.xwss.callback.SpringPlainTextPasswordValidationCallbackHandler">
<property name="authenticationManager" ref="authenticationManager"/>
</bean>
<bean id="authenticationManager" class="org.springframework.security.providers.ProviderManager">
<property name="providers">
<bean class="org.springframework.security.providers.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userDetailsService"/>
</bean>
</property>
</bean>
<bean id="userDetailsService" class="com.mycompany.app.dao.UserDetailService" />
...
</beans>
Using JaasPlainTextPasswordValidationCallbackHandler
The JaasPlainTextPasswordValidationCallbackHandler
is based on the standard Java Authentication and Authorization Service. It is beyond the scope of this document to provide a full introduction into JAAS, but a good tutorial is available.
The JaasPlainTextPasswordValidationCallbackHandler
requires only a loginContextName
to operate. It creates a new JAAS LoginContext
by using this name and handles the standard JAAS NameCallback
and PasswordCallback
by using the username and password provided in the SOAP message. This means that this callback handler integrates with any JAAS LoginModule
that fires these callbacks during the login()
phase, which is standard behavior.
You can wire up a JaasPlainTextPasswordValidationCallbackHandler
as follows:
<bean id="jaasValidationHandler"
class="org.springframework.ws.soap.security.xwss.callback.jaas.JaasPlainTextPasswordValidationCallbackHandler">
<property name="loginContextName" value="MyLoginModule" />
</bean>
In this case, the callback handler uses the LoginContext
named MyLoginModule
. This module should be defined in your jaas.config
file, as explained in the tutorial mentioned earlier.
Digest Username Authentication
When using password digests, the SOAP message also contains a UsernameToken
element, which itself contains a Username
element and a Password
element. The difference is that the password is not sent as plain text, but as a digest. The recipient compares this digest to the digest he calculated from the known password of the user, and, if they are the same, the user is authenticated. This method is comparable to the digest authentication provided by HTTP servers.
To require that every incoming message contains a UsernameToken
element with a password digest, the security policy file should contain a RequireUsernameToken
element, with the passwordDigestRequired
attribute set to true
. Additionally, the nonceRequired
attribute should be set to true
: You can find a reference of possible child elements here. The following listing shows how to define a RequireUsernameToken
element:
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
...
<xwss:RequireUsernameToken passwordDigestRequired="true" nonceRequired="true"/>
...
</xwss:SecurityConfiguration>
If the username token is not present, the XwsSecurityInterceptor
returns a SOAP fault to the sender. If it is present, it fires a PasswordValidationCallback
with a DigestPasswordRequest
to the registered handlers. Within Spring-WS, two classes handle this particular callback: SimplePasswordValidationCallbackHandler
and SpringDigestPasswordValidationCallbackHandler
.
Using SimplePasswordValidationCallbackHandler
The SimplePasswordValidationCallbackHandler
can handle both plain text passwords as well as password digests. It is described in Using SimplePasswordValidationCallbackHandler
.
Using SpringDigestPasswordValidationCallbackHandler
The SpringDigestPasswordValidationCallbackHandler
requires a Spring Security UserDetailService
to operate. It uses this service to retrieve the password of the user specified in the token. The digest of the password contained in this details object is then compared with the digest in the message. If they are equal, the user has successfully authenticated, and a UsernamePasswordAuthenticationToken
is stored in the SecurityContextHolder
. You can set the service by using the userDetailsService
property. Additionally, you can set a userCache
property, to cache loaded user details. The following example shows how to do so:
<beans>
<bean class="org.springframework.ws.soap.security.xwss.callback.SpringDigestPasswordValidationCallbackHandler">
<property name="userDetailsService" ref="userDetailsService"/>
</bean>
<bean id="userDetailsService" class="com.mycompany.app.dao.UserDetailService" />
...
</beans>
Certificate Authentication
A more secure way of authentication uses X509 certificates. In this scenario, the SOAP message contains a`BinarySecurityToken`, which contains a Base 64-encoded version of a X509 certificate. The certificate is used by the recipient to authenticate. The certificate stored in the message is also used to sign the message (see Verifying Signatures).
To make sure that all incoming SOAP messages carry a`BinarySecurityToken`, the security policy file should contain a RequireSignature
element. This element can further carry other elements, which are covered in Verifying Signatures. You can find a reference of possible child elements here. The following listing shows how to define a RequireSignature
element:
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
...
<xwss:RequireSignature requireTimestamp="false">
...
</xwss:SecurityConfiguration>
When a message arrives that carries no certificate, the XwsSecurityInterceptor
returns a SOAP fault to the sender. If it is present, it fires a CertificateValidationCallback
. Three handlers within Spring-WS handle this callback for authentication purposes:
In most cases, certificate authentication should be preceded by certificate validation, since you want to authenticate against only valid certificates. Invalid certificates, such as certificates for which the expiration date has passed or which are not in your store of trusted certificates, should be ignored.
In Spring-WS terms, this means that the SpringCertificateValidationCallbackHandler
or JaasCertificateValidationCallbackHandler
should be preceded by KeyStoreCallbackHandler
. This can be accomplished by setting the order of the callbackHandlers
property in the configuration of the XwsSecurityInterceptor
:
<bean id="wsSecurityInterceptor"
class="org.springframework.ws.soap.security.xwss.XwsSecurityInterceptor">
<property name="policyConfiguration" value="classpath:securityPolicy.xml"/>
<property name="callbackHandlers">
<list>
<ref bean="keyStoreHandler"/>
<ref bean="springSecurityHandler"/>
</list>
</property>
</bean>
Using this setup, the interceptor first determines if the certificate in the message is valid buusing the keystore and then authenticating against it.
Using KeyStoreCallbackHandler
The KeyStoreCallbackHandler
uses a standard Java keystore to validate certificates. This certificate validation process consists of the following steps: .
-
The handler checks whether the certificate is in the private keyStore
. If it is, it is valid.
-
If the certificate is not in the private keystore, the handler checks whether the current date and time are within the validity period given in the certificate. If they are not, the certificate is invalid. If it is, it continues with the final step.
-
A certification path for the certificate is created. This basically means that the handler determines whether the certificate has been issued by any of the certificate authorities in the trustStore
. If a certification path can be built successfully, the certificate is valid. Otherwise, the certificate is not valid.
To use the KeyStoreCallbackHandler
for certificate validation purposes, you most likely need to set only the trustStore
property:
<beans>
<bean id="keyStoreHandler" class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallbackHandler">
<property name="trustStore" ref="trustStore"/>
</bean>
<bean id="trustStore" class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="location" value="classpath:truststore.jks"/>
<property name="password" value="changeit"/>
</bean>
</beans>
Using the setup shown in the preceding example, the certificate that is to be validated must be in the trust store itself or the trust store must contain a certificate authority that issued the certificate.
Using SpringCertificateValidationCallbackHandler
The SpringCertificateValidationCallbackHandler
requires an Spring Security AuthenticationManager
to operate. It uses this manager to authenticate against a X509AuthenticationToken
that it creates. The configured authentication manager is expected to supply a provider that can handle this token (usually an instance of X509AuthenticationProvider
). If authentication is successful, the token is stored in the SecurityContextHolder
. You can set the authentication manager by using the authenticationManager
property:
<beans>
<bean id="springSecurityCertificateHandler"
class="org.springframework.ws.soap.security.xwss.callback.SpringCertificateValidationCallbackHandler">
<property name="authenticationManager" ref="authenticationManager"/>
</bean>
<bean id="authenticationManager"
class="org.springframework.security.providers.ProviderManager">
<property name="providers">
<bean class="org.springframework.ws.soap.security.x509.X509AuthenticationProvider">
<property name="x509AuthoritiesPopulator">
<bean class="org.springframework.ws.soap.security.x509.populator.DaoX509AuthoritiesPopulator">
<property name="userDetailsService" ref="userDetailsService"/>
</bean>
</property>
</bean>
</property>
</bean>
<bean id="userDetailsService" class="com.mycompany.app.dao.UserDetailService" />
...
</beans>
In this case, we use a custom user details service to obtain authentication details based on the certificate. See the Spring Security reference documentation for more information about authentication against X509 certificates.
Using JaasCertificateValidationCallbackHandler
The JaasCertificateValidationCallbackHandler
requires a loginContextName
to operate. It creates a new JAAS LoginContext
by using this name and the X500Principal
of the certificate. This means that this callback handler integrates with any JAAS LoginModule
that handles X500 principals.
You can wire up a JaasCertificateValidationCallbackHandler
as follows:
<bean id="jaasValidationHandler"
class="org.springframework.ws.soap.security.xwss.callback.jaas.JaasCertificateValidationCallbackHandler">
<property name="loginContextName">MyLoginModule</property>
</bean>
In this case, the callback handler uses the LoginContext
named MyLoginModule
. This module should be defined in your jaas.config
file and should be able to authenticate against X500 principals.
7.1.3. Digital Signatures
The digital signature of a message is a piece of information based on both the document and the signer’s private key. Two main tasks are related to signatures in WS-Security: verifying signatures and signing messages.
Verifying Signatures
As with certificate-based authentication, a signed message contains a BinarySecurityToken
, which contains the certificate used to sign the message. Additionally, it contains a SignedInfo
block, which indicates what part of the message was signed.
To make sure that all incoming SOAP messages carry a BinarySecurityToken
, the security policy file should contain a RequireSignature
element. It can also contain a SignatureTarget
element, which specifies the target message part that was expected to be signed and various other subelements. You can also define the private key alias to use, whether to use a symmetric instead of a private key, and many other properties. You can find a reference of possible child elements here. The following listing configures a RequireSignature
element:
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
<xwss:RequireSignature requireTimestamp="false"/>
</xwss:SecurityConfiguration>
If the signature is not present, the XwsSecurityInterceptor
returns a SOAP fault to the sender. If it is present, it fires a SignatureVerificationKeyCallback
to the registered handlers. Within Spring-WS, one class handles this particular callback: KeyStoreCallbackHandler
.
Using KeyStoreCallbackHandler
As described in KeyStoreCallbackHandler, KeyStoreCallbackHandler
uses a java.security.KeyStore
for handling various cryptographic callbacks, including signature verification. For signature verification, the handler uses the trustStore
property:
<beans>
<bean id="keyStoreHandler" class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallbackHandler">
<property name="trustStore" ref="trustStore"/>
</bean>
<bean id="trustStore" class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="location" value="classpath:org/springframework/ws/soap/security/xwss/test-truststore.jks"/>
<property name="password" value="changeit"/>
</bean>
</beans>
Signing Messages
When signing a message, the XwsSecurityInterceptor
adds the BinarySecurityToken
to the message. It also adds a SignedInfo
block, which indicates what part of the message was signed.
To sign all outgoing SOAP messages, the security policy file should contain a Sign
element. It can also contain a SignatureTarget
element, which specifies the target message part that was expected to be signed and various other subelements. You can also define the private key alias to use, whether to use a symmetric instead of a private key, and many other properties. You can find a reference of possible child elements here. The following example includes a Sign
element:
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
<xwss:Sign includeTimestamp="false" />
</xwss:SecurityConfiguration>
The XwsSecurityInterceptor
fires a SignatureKeyCallback
to the registered handlers. Within Spring-WS, the KeyStoreCallbackHandler
class handles this particular callback.
Using KeyStoreCallbackHandler
As described in KeyStoreCallbackHandler, the KeyStoreCallbackHandler
uses a java.security.KeyStore
to handle various cryptographic callbacks, including signing messages. For adding signatures, the handler uses the keyStore
property. Additionally, you must set the privateKeyPassword
property to unlock the private key used for signing. The following example uses a KeyStoreCallbackHandler
:
<beans>
<bean id="keyStoreHandler" class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallbackHandler">
<property name="keyStore" ref="keyStore"/>
<property name="privateKeyPassword" value="changeit"/>
</bean>
<bean id="keyStore" class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="location" value="classpath:keystore.jks"/>
<property name="password" value="changeit"/>
</bean>
</beans>
7.1.4. Decryption and Encryption
When encrypting, the message is transformed into a form that can be read only with the appropriate key. The message can be decrypted to reveal the original, readable message.
Decryption
To decrypt incoming SOAP messages, the security policy file should contain a RequireEncryption
element. This element can further carry a EncryptionTarget
element that indicates which part of the message should be encrypted and a SymmetricKey
to indicate that a shared secret instead of the regular private key should be used to decrypt the message. You can read a description of the other elements here. The following example uses a RequireEncryption
element:
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
<xwss:RequireEncryption />
</xwss:SecurityConfiguration>
If an incoming message is not encrypted, the XwsSecurityInterceptor
returns a SOAP ault to the sender. If it is present, it fires a DecryptionKeyCallback
to the registered handlers. Within Spring-WS, the KeyStoreCallbackHandler
class handles this particular callback.
Using KeyStoreCallbackHandler
As described in KeyStoreCallbackHandler, the KeyStoreCallbackHandler
uses a java.security.KeyStore
to handle various cryptographic callbacks, including decryption. For decryption, the handler uses the keyStore
property. Additionally, you must set the privateKeyPassword
property to unlock the private key used for decryption. For decryption based on symmetric keys, it uses the symmetricStore
. The following example uses KeyStoreCallbackHandler
:
<beans>
<bean id="keyStoreHandler" class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallbackHandler">
<property name="keyStore" ref="keyStore"/>
<property name="privateKeyPassword" value="changeit"/>
</bean>
<bean id="keyStore" class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="location" value="classpath:keystore.jks"/>
<property name="password" value="changeit"/>
</bean>
</beans>
Encryption
To encrypt outgoing SOAP messages, the security policy file should contain an Encrypt
element. This element can further carry a EncryptionTarget
element that indicates which part of the message should be encrypted and a SymmetricKey
to indicate that a shared secret instead of the regular public key should be used to encrypt the message. You can read a description of the other elements here. The following example uses an Encrypt
element:
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
<xwss:Encrypt />
</xwss:SecurityConfiguration>
The XwsSecurityInterceptor
fires an EncryptionKeyCallback
to the registered handlers to retrieve the encryption information. Within Spring-WS, the KeyStoreCallbackHandler
class handles this particular callback.
Using KeyStoreCallbackHandler
As described in KeyStoreCallbackHandler, the KeyStoreCallbackHandler
uses a java.security.KeyStore
to handle various cryptographic callbacks, including encryption. For encryption based on public keys, the handler uses the trustStore
property. For encryption based on symmetric keys, it uses symmetricStore
. The following example uses KeyStoreCallbackHandler
:
<beans>
<bean id="keyStoreHandler" class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallbackHandler">
<property name="trustStore" ref="trustStore"/>
</bean>
<bean id="trustStore" class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="location" value="classpath:truststore.jks"/>
<property name="password" value="changeit"/>
</bean>
</beans>
7.1.5. Security Exception Handling
When a securement or validation action fails, the XwsSecurityInterceptor
throws a WsSecuritySecurementException
or WsSecurityValidationException
respectively. These exceptions bypass the standard exception handling mechanism but are handled by the interceptor itself.
WsSecuritySecurementException
exceptions are handled by the handleSecurementException
method of the XwsSecurityInterceptor
. By default, this method logs an error and stops further processing of the message.
Similarly, WsSecurityValidationException
exceptions are handled by the handleValidationException
method of the XwsSecurityInterceptor
. By default, this method creates a SOAP 1.1 Client or SOAP 1.2 sender fault and sends that back as a response.
Both handleSecurementException
and handleValidationException
are protected methods, which you can override to change their default behavior.
7.2. Using Wss4jSecurityInterceptor
The Wss4jSecurityInterceptor
is an EndpointInterceptor
(see Intercepting Requests — the EndpointInterceptor
Interface) that is based on Apache’s WSS4J.
WSS4J implements the following standards:
-
OASIS Web Services Security: SOAP Message Security 1.0 Standard 200401, March 2004
-
Username Token profile V1.0
-
X.509 Token Profile V1.0
This interceptor supports messages created by the AxiomSoapMessageFactory
and the SaajSoapMessageFactory
.
7.2.1. Configuring Wss4jSecurityInterceptor
WSS4J uses no external configuration file. The interceptor is entirely configured by properties. The validation and securement actions invoked by this interceptor are specified via validationActions
and securementActions
properties, respectively. Actions are passed as a space-separated strings. The following listing shows an example configuration:
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="validationActions" value="UsernameToken Encrypt"/>
...
<property name="securementActions" value="Encrypt"/>
...
</bean>
The following table shows the available validation actions:
Validation action
Description
UsernameToken
Validates username token
Timestamp
Validates the timestamp
Encrypt
Decrypts the message
Signature
Validates the signature
NoSecurity
No action performed
The following table shows the available securement actions:
Securement action
Description
UsernameToken
Adds a username token
UsernameTokenSignature
Adds a username token and a signature username token secret key
Timestamp
Adds a timestamp
Encrypt
Encrypts the response
Signature
Signs the response
NoSecurity
No action performed
The order of the actions is significant and is enforced by the interceptor. If its security actions were performed in a different order than the one specified by`validationActions`, the interceptor rejects an incoming SOAP message.
7.2.2. Handling Digital Certificates
For cryptographic operations that require interaction with a keystore or certificate handling (signature, encryption, and decryption operations), WSS4J requires an instance of`org.apache.ws.security.components.crypto.Crypto`.
Crypto
instances can be obtained from WSS4J’s CryptoFactory
or more conveniently with the Spring-WS`CryptoFactoryBean`.
CryptoFactoryBean
Spring-WS provides a convenient factory bean, CryptoFactoryBean
, that constructs and configures Crypto
instances through strongly typed properties (preferred) or through a Properties
object.
By default, CryptoFactoryBean
returns instances of org.apache.ws.security.components.crypto.Merlin
. You can change this by setting the cryptoProvider
property (or its equivalent org.apache.ws.security.crypto.provider
string property).
The following example configuration uses CryptoFactoryBean
:
<bean class="org.springframework.ws.soap.security.wss4j.support.CryptoFactoryBean">
<property name="keyStorePassword" value="mypassword"/>
<property name="keyStoreLocation" value="file:/path_to_keystore/keystore.jks"/>
</bean>
7.2.3. Authentication
This section addresses how to do authentication with Wss4jSecurityInterceptor
.
Validating Username Token
Spring-WS provides a set of callback handlers to integrate with Spring Security. Additionally, a simple callback handler, SimplePasswordValidationCallbackHandler
, is provided to configure users and passwords with an in-memory Properties
object.
Callback handlers are configured through the validationCallbackHandler
of the Wss4jSecurityInterceptor
property.
Using SimplePasswordValidationCallbackHandler
SimplePasswordValidationCallbackHandler
validates plain text and digest username tokens against an in-memory Properties
object. You can configure it as follows:
<bean id="callbackHandler"
class="org.springframework.ws.soap.security.wss4j.callback.SimplePasswordValidationCallbackHandler">
<property name="users">
<props>
<prop key="Bert">Ernie</prop>
</props>
</property>
</bean>
Using SpringSecurityPasswordValidationCallbackHandler
The SpringSecurityPasswordValidationCallbackHandler
validates plain text and digest passwords by using a Spring Security UserDetailService
to operate. It uses this service to retrieve the the password (or a digest of the password) of the user specified in the token. The password (or a digest of the password) contained in this details object is then compared with the digest in the message. If they are equal, the user has successfully authenticated, and a UsernamePasswordAuthenticationToken
is stored in the`SecurityContextHolder`. You can set the service by using the userDetailsService
. Additionally, you can set a userCache
property, to cache loaded user details, as follows:
<beans>
<bean class="org.springframework.ws.soap.security.wss4j.callback.SpringDigestPasswordValidationCallbackHandler">
<property name="userDetailsService" ref="userDetailsService"/>
</bean>
<bean id="userDetailsService" class="com.mycompany.app.dao.UserDetailService" />
...
</beans>
Adding Username Token
Adding a username token to an outgoing message is as simple as adding UsernameToken
to the securementActions
property of the Wss4jSecurityInterceptor
and specifying securementUsername
and`securementPassword`.
The password type can be set by setting the securementPasswordType
property. Possible values are PasswordText
for plain text passwords or PasswordDigest
for digest passwords, which is the default.
The following example generates a username token with a digest password:
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="securementActions" value="UsernameToken"/>
<property name="securementUsername" value="Ernie"/>
<property name="securementPassword" value="Bert"/>
</bean>
If the plain text password type is chosen, it is possible to instruct the interceptor to add Nonce
and Created
elements by setting the securementUsernameTokenElements
property. The value must be a list that contains the desired elements' names separated by spaces (case sensitive).
The following example generates a username token with a plain text password, a Nonce
, and a Created
element:
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="securementActions" value="UsernameToken"/>
<property name="securementUsername" value="Ernie"/>
<property name="securementPassword" value="Bert"/>
<property name="securementPasswordType" value="PasswordText"/>
<property name="securementUsernameTokenElements" value="Nonce Created"/>
</bean>
Certificate Authentication
As certificate authentication is akin to digital signatures, WSS4J handles it as part of the signature validation and securement. Specifically, the securementSignatureKeyIdentifier
property must be set to DirectReference
in order to instruct WSS4J to generate a BinarySecurityToken
element containing the X509 certificate and to include it in the outgoing message. The certificate’s name and password are passed through the securementUsername
and securementPassword
properties, respectively, as the following example shows:
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="securementActions" value="Signature"/>
<property name="securementSignatureKeyIdentifier" value="DirectReference"/>
<property name="securementUsername" value="mycert"/>
<property name="securementPassword" value="certpass"/>
<property name="securementSignatureCrypto">
<bean class="org.springframework.ws.soap.security.wss4j.support.CryptoFactoryBean">
<property name="keyStorePassword" value="123456"/>
<property name="keyStoreLocation" value="classpath:/keystore.jks"/>
</bean>
</property>
</bean>
For the certificate validation, regular signature validation applies:
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="validationActions" value="Signature"/>
<property name="validationSignatureCrypto">
<bean class="org.springframework.ws.soap.security.wss4j.support.CryptoFactoryBean">
<property name="keyStorePassword" value="123456"/>
<property name="keyStoreLocation" value="classpath:/keystore.jks"/>
</bean>
</property>
</bean>
At the end of the validation, the interceptor automatically verifies the validity of the certificate by delegating to the default WSS4J implementation. If needed, you can change this behavior by redefining the verifyCertificateTrust
method.
For more detail, see to Digital Signatures.
7.2.4. Security Timestamps
This section describes the various timestamp options available in the Wss4jSecurityInterceptor
.
Validating Timestamps
To validate timestamps, add Timestamp
to the validationActions
property. You can override timestamp semantics specified by the initiator of the SOAP message by setting timestampStrict
to true
and specifying a server-side time-to-live in seconds (default: 300) by setting the timeToLive
property. The interceptor always rejects already expired timestamps, whatever the value of timeToLive
is.
In the following example, the interceptor limits the timestamp validity window to 10 seconds, rejecting any valid timestamp token outside that window:
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="validationActions" value="Timestamp"/>
<property name="timestampStrict" value="true"/>
<property name="timeToLive" value="10"/>
</bean>
Adding Timestamps
Adding Timestamp
to the securementActions
property generates a timestamp header in outgoing messages. The timestampPrecisionInMilliseconds
property specifies whether the precision of the generated timestamp is in milliseconds. The default value is true
. The following listing adds a timestamp:
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="securementActions" value="Timestamp"/>
<property name="timestampPrecisionInMilliseconds" value="true"/>
</bean>
7.2.5. Digital Signatures
This section describes the various signature options available in the Wss4jSecurityInterceptor
.
Verifying Signatures
To instruct the Wss4jSecurityInterceptor
, validationActions
must contain the Signature
action. Additionally, the validationSignatureCrypto
property must point to the keystore containing the public certificates of the initiator:
<bean id="wsSecurityInterceptor" class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="validationActions" value="Signature"/>
<property name="validationSignatureCrypto">
<bean class="org.springframework.ws.soap.security.wss4j.support.CryptoFactoryBean">
<property name="keyStorePassword" value="123456"/>
<property name="keyStoreLocation" value="classpath:/keystore.jks"/>
</bean>
</property>
</bean>
Signing Messages
Signing outgoing messages is enabled by adding the Signature
action to the securementActions
. The alias and the password of the private key to use are specified by the securementUsername
and securementPassword
properties, respectively. securementSignatureCrypto
must point to the keystore that contains the private key:
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="securementActions" value="Signature"/>
<property name="securementUsername" value="mykey"/>
<property name="securementPassword" value="123456"/>
<property name="securementSignatureCrypto">
<bean class="org.springframework.ws.soap.security.wss4j.support.CryptoFactoryBean">
<property name="keyStorePassword" value="123456"/>
<property name="keyStoreLocation" value="classpath:/keystore.jks"/>
</bean>
</property>
</bean>
Furthermore, you can define the signature algorithm by setting the securementSignatureAlgorithm
property.
You can customize the key identifier type to use by setting the securementSignatureKeyIdentifier
property. Only IssuerSerial
and DirectReference
are valid for the signature.
The securementSignatureParts
property controls which part of the message is signed. The value of this property is a list of semicolon-separated element names that identify the elements to sign. The general form of a signature part is {}{namespace}Element
. Note that the first empty brackets are used for encryption parts only. The default behavior is to sign the SOAP body.
The following example shows how to sign the echoResponse
element in the Spring Web Services echo sample:
<property name="securementSignatureParts"
value="{}{http://www.springframework.org/spring-ws/samples/echo}echoResponse"/>
To specify an element without a namespace, use the string, Null
(case sensitive), as the namespace name.
If no other element in the request has a local name of Body
, the SOAP namespace identifier can be empty ({}
).
Signature Confirmation
Signature confirmation is enabled by setting enableSignatureConfirmation
to true
. Note that the signature confirmation action spans over the request and the response. This implies that secureResponse
and validateRequest
must be set to true
(which is the default value) even if there are no corresponding security actions. The following example sets the enableSignatureConfirmation
property to true
:
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="validationActions" value="Signature"/>
<property name="enableSignatureConfirmation" value="true"/>
<property name="validationSignatureCrypto">
<bean class="org.springframework.ws.soap.security.wss4j.support.CryptoFactoryBean">
<property name="keyStorePassword" value="123456"/>
<property name="keyStoreLocation" value="file:/keystore.jks"/>
</bean>
</property>
</bean>
7.2.6. Decryption and Encryption
This section describes the various decryption and encryption options available in the Wss4jSecurityInterceptor
.
Decryption
Decryption of incoming SOAP messages requires that the Encrypt
action be added to the validationActions
property. The rest of the configuration depends on the key information that appears in the message. (This is because WSS4J needs only a Crypto for encypted keys, whereas embedded key name validation is delegated to a callback handler.)
To decrypt messages with an embedded encrypted symmetric key (the xenc:EncryptedKey
element), validationDecryptionCrypto
needs to point to a keystore that contains the decryption private key. Additionally, validationCallbackHandler
has to be injected with a org.springframework.ws.soap.security.wss4j.callback.KeyStoreCallbackHandler
that specifies the key’s password:
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="validationActions" value="Encrypt"/>
<property name="validationDecryptionCrypto">
<bean class="org.springframework.ws.soap.security.wss4j.support.CryptoFactoryBean">
<property name="keyStorePassword" value="123456"/>
<property name="keyStoreLocation" value="classpath:/keystore.jks"/>
</bean>
</property>
<property name="validationCallbackHandler">
<bean class="org.springframework.ws.soap.security.wss4j.callback.KeyStoreCallbackHandler">
<property name="privateKeyPassword" value="mykeypass"/>
</bean>
</property>
</bean>
To support decryption of messages with an embedded key name ( ds:KeyName
element), you can configure a KeyStoreCallbackHandler
that points to the keystore with the symmetric secret key. The symmetricKeyPassword
property indicates the key’s password, the key name being the one specified by ds:KeyName
element:
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="validationActions" value="Encrypt"/>
<property name="validationCallbackHandler">
<bean class="org.springframework.ws.soap.security.wss4j.callback.KeyStoreCallbackHandler">
<property name="keyStore">
<bean class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="location" value="classpath:keystore.jks"/>
<property name="type" value="JCEKS"/>
<property name="password" value="123456"/>
</bean>
</property>
<property name="symmetricKeyPassword" value="mykeypass"/>
</bean>
</property>
</bean>
Encryption
Adding Encrypt
to the securementActions
enables encryption of outgoing messages. You can set the certificate’s alias to use for the encryption by setting the securementEncryptionUser
property. The keystore where the certificate resides is accessed through the securementEncryptionCrypto
property. As encryption relies on public certificates, no password needs to be passed. The following example uses the securementEncryptionCrypto
property:
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="securementActions" value="Encrypt"/>
<property name="securementEncryptionUser" value="mycert"/>
<property name="securementEncryptionCrypto">
<bean class="org.springframework.ws.soap.security.wss4j.support.CryptoFactoryBean">
<property name="keyStorePassword" value="123456"/>
<property name="keyStoreLocation" value="file:/keystore.jks"/>
</bean>
</property>
</bean>
You can customize encryption in several ways: The key identifier type to use is defined by the securementEncryptionKeyIdentifier
property. Possible values are IssuerSerial
,X509KeyIdentifier
, DirectReference
,Thumbprint
, SKIKeyIdentifier
, and EmbeddedKeyName
.
If you choose the EmbeddedKeyName
type, you need to specify the secret key to use for the encryption. The alias of the key is set in the securementEncryptionUser
property, as for the other key identifier types. However, WSS4J requires a callback handler to fetch the secret key. Thus, you must provide securementCallbackHandler
with a KeyStoreCallbackHandler
that points to the appropriate keystore. By default, the ds:KeyName
element in the resulting WS-Security header takes the value of the securementEncryptionUser
property. To indicate a different name, you can set the securementEncryptionEmbeddedKeyName
with the desired value. In the next example, the outgoing message is encrypted with a key aliased secretKey
, whereas myKey
appears in ds:KeyName
element:
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="securementActions" value="Encrypt"/>
<property name="securementEncryptionKeyIdentifier" value="EmbeddedKeyName"/>
<property name="securementEncryptionUser" value="secretKey"/>
<property name="securementEncryptionEmbeddedKeyName" value="myKey"/>
<property name="securementCallbackHandler">
<bean class="org.springframework.ws.soap.security.wss4j.callback.KeyStoreCallbackHandler">
<property name="symmetricKeyPassword" value="keypass"/>
<property name="keyStore">
<bean class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="location" value="file:/keystore.jks"/>
<property name="type" value="jceks"/>
<property name="password" value="123456"/>
</bean>
</property>
</bean>
</property>
</bean>
The securementEncryptionKeyTransportAlgorithm
property defines which algorithm to use to encrypt the generated symmetric key. Supported values are http://www.w3.org/2001/04/xmlenc#rsa-1_5
, which is the default, and http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p
.
You can set the symmetric encryption algorithm to use by setting the securementEncryptionSymAlgorithm
property. Supported values are http://www.w3.org/2001/04/xmlenc#aes128-cbc
(default), http://www.w3.org/2001/04/xmlenc#tripledes-cbc
, http://www.w3.org/2001/04/xmlenc#aes256-cbc
, and http://www.w3.org/2001/04/xmlenc#aes192-cbc
.
Finally, the securementEncryptionParts
property defines which parts of the message are encrypted. The value of this property is a list of semicolon-separated element names that identify the elements to encrypt. An encryption mode specifier and a namespace identification, each inside a pair of curly brackets, may precede each element name. The encryption mode specifier is either {Content}
or {Element}
See the W3C XML Encryption specification about the differences between Element and Content encryption. The following example identifies the echoResponse
from the echo sample:
<property name="securementEncryptionParts"
value="{Content}{http://www.springframework.org/spring-ws/samples/echo}echoResponse"/>
Be aware that the element name, the namespace identifier, and the encryption modifier are case-sensitive. You can omit the encryption modifier and the namespace identifier. If you do, the encryption mode defaults to Content
, and the namespace is set to the SOAP namespace.
To specify an element without a namespace, use the value, Null
(case sensitive), as the namespace name. If no list is specified, the handler encrypts the SOAP Body in Content
mode by default.
7.2.7. Security Exception Handling
The exception handling of the Wss4jSecurityInterceptor
is identical to that of the XwsSecurityInterceptor
. See Security Exception Handling for more information.