Rohit Girme
Rohit Girme

Reputation: 89

How to include SOAP authentication details in header?

This is my SOAP request

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Header>
        <Security>
            <UsernameToken>
                <SiteId>testlab1</SiteId>
                <Password>abcd1234</Password>
            </UsernameToken>
        </Security>
    </SOAP-ENV:Header>
    <SOAP-ENV:Body 
    xmlns:ns3="http://www.foo.bar/ws"
    xmlns:ns5="http://http://www.foo.bar.com" 
    xmlns:ns4="http://schemas.xmlsoap.org/soap/envelope">
        <ns5:RequestObject>
            <ns3:Header>
                <AccountNo>4353454543</AccountNo>
                <CustomerId>534534</CustomerId>
                <SiteId>testlab1</SiteId>
                <RegisterId>0</RegisterId>
                <SequenceNumber>1</SequenceNumber>
                <Retry>0</Retry>
            </ns3:Header>
        </ns5:RequestObject>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

It works with SOAP UI tool. But when it is auto-generated with spring-ws's WebServiceTemplate it does not include :

<Security>
   <UsernameToken>
        <SiteId>testlab1</SiteId>
        <Password>abcd1234</Password>
   </UsernameToken>
</Security>

part in <SOAP-ENV:Header>. Is there any that I can include these authentication details through my code? Any help will be greatly appreciated !!

Upvotes: 4

Views: 530

Answers (1)

a3765910
a3765910

Reputation: 354

If you are using spring-ws's WebServiceTemplate then you can try adding WebServiceMessageCallback and override doWithMessage(). Something like :

getWebServiceTemplate().marshalSendAndReceive("https://soap.endpoint",
    requestObj, new WebServiceMessageCallback() {

                    public void doWithMessage(WebServiceMessage message) {
                        try {
                            SoapMessage soapMessage = (SoapMessage)message;
                            SoapHeader header = soapMessage.getSoapHeader();
                            StringSource headerSource = new StringSource("<Security><UsernameToken><SiteId>testlab1</SiteId>"+
"<Password>abcd1234</Password></UsernameToken></Security> ");
                            Transformer transformer = TransformerFactory.newInstance().newTransformer();
                            transformer.transform(headerSource, header.getResult());
                        } catch (Exception e) {
                            // exception handling
                        }
                    }
                });

Hope that solve your requirement here!

Upvotes: 2

Related Questions