Spring WS Add Soap Header In Client

本文介绍如何使用Spring WS在客户端添加SOAP Header。通过创建自定义的`Authentication`类并实现`WebServiceMessageCallback`接口,可以将认证信息作为SOAP Header的一部分发送到服务器。

Spring WS Add Soap Header In Client

BY MEMORYNOTFOUND · MARCH 25, 2016

Sometimes you need to pass a soap header from the client to the server. This header can contain security information or other meta data. This example shows you how to add a soap header in the client using Spring WS.

We are using JAX-B to marshal the following object into the SOAP Header.

package com.memorynotfound.client;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(namespace = Authentication.AUTH_NS)
public class Authentication {

    public static final String AUTH_NS = "http://memorynotfound.com/security";

    @XmlElement(namespace = AUTH_NS)
    private String username;
    @XmlElement(namespace = AUTH_NS)
    private String password;

    public Authentication() {
    }

    public Authentication(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

You can optionally add a package-info.java file to configure JAX-B to change the namespace prefix. In this example we changed the namespace prefix to auth.

@XmlSchema(
        namespace = BeerEndpoint.NAMESPACE_URI,
        elementFormDefault = XmlNsForm.QUALIFIED,
        xmlns = {
                @XmlNs(prefix="auth", namespaceURI = Authentication.AUTH_NS)
        }
)

package com.memorynotfound.client;

import com.memorynotfound.server.BeerEndpoint;
import javax.xml.bind.annotation.*;

Next, we create the SecurityHeader which implements the WebServiceMessageCallback interface. This allows us to override the doWithMessage() in which we can retrieve the SoapHeader and we marshal our custom Authentication object into the SOAP Header.

package com.memorynotfound.client;

import org.springframework.ws.WebServiceMessage;
import org.springframework.ws.client.core.WebServiceMessageCallback;
import org.springframework.ws.soap.SoapHeader;
import org.springframework.ws.soap.SoapMessage;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.transform.TransformerException;
import java.io.IOException;

public class SecurityHeader implements WebServiceMessageCallback {

    private Authentication authentication;

    public SecurityHeader(Authentication authentication) {
        this.authentication = authentication;
    }

    @Override
    public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException {
        SoapHeader soapHeader = ((SoapMessage)message).getSoapHeader();

        try {
            JAXBContext context = JAXBContext.newInstance(Authentication.class);

            Marshaller marshaller = context.createMarshaller();
            marshaller.marshal(authentication, soapHeader.getResult());

        } catch (JAXBException e) {
            throw new IOException("error while marshalling authentication.");
        }
    }
}

When we send the request using the WebServiceTemplate obtained from the WebServiceGetewaySupport, we pass in our custom SecurityHeader callback with an instance of the Authentication object. This callback is responsible for adding the SOAP Header to the request in the client.

package com.memorynotfound.client;

import com.memorynotfound.beer.GetBeerRequest;
import com.memorynotfound.beer.GetBeerResponse;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;

public class BeerClient extends WebServiceGatewaySupport {

    public GetBeerResponse getBeer(int id) {
        GetBeerRequest request = new GetBeerRequest();
        request.setId(id);
        return (GetBeerResponse) getWebServiceTemplate()
                .marshalSendAndReceive(request,
                        new SecurityHeader(
                                new Authentication("username", "password")));
    }
}

Last step is to configure the client using spring and java configuration.

package com.memorynotfound.client;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;

@Configuration
public class SoapClientConfig {

    @Bean
    public Jaxb2Marshaller marshaller() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setContextPath("com.memorynotfound.beer");
        return marshaller;
    }

    @Bean
    public BeerClient weatherClient(Jaxb2Marshaller marshaller) {
        BeerClient client = new BeerClient();
        client.setDefaultUri("http://localhost:8080/ws/beer");
        client.setMarshaller(marshaller);
        client.setUnmarshaller(marshaller);
        return client;
    }

}

Finally, we can run the server. When we make the following request, the SOAP Header is added to the clients request.

package com.memorynotfound.client;

import com.memorynotfound.beer.GetBeerResponse;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class RunClient {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SoapClientConfig.class);
        BeerClient client = context.getBean(BeerClient.class);
        GetBeerResponse response = client.getBeer(1);
    }

}

Example Request

When we execute the previous client, we can see that we have sent the following request.

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Header>
      <auth:authentication xmlns:auth="http://memorynotfound.com/security" xmlns:beer="http://memorynotfound.com/beer">
         <auth:username>username</auth:username>
         <auth:password>password</auth:password>
      </auth:authentication>
   </SOAP-ENV:Header>
   <SOAP-ENV:Body>
      <ns2:getBeerRequest xmlns:ns2="http://memorynotfound.com/beer">
         <ns2:id>1</ns2:id>
      </ns2:getBeerRequest>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

转载于:https://my.oschina.net/itwangxinli/blog/850695

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值