Sign JAX-WS SOAP request
Asked Answered
B

4

27

I would like to write a JAX-WS web service that signs my SOAP messages using the http://www.w3.org/TR/xmldsig-core/ recommendation.

With what I found on the internet I wrote a JAX-WS handler (SOAPHandler<SOAPMessageContext>) that manages to change a copy of the SOAP request:

@Override
public boolean handleMessage(SOAPMessageContext smc) {
    Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    SOAPMessage message = smc.getMessage();

    if (outboundProperty) {
        try {
            SOAPPart soapPart = message.getSOAPPart();
            SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

            Source source = soapPart.getContent();

            Node root = null;
            Document doc22 = null;
            if (source instanceof DOMSource) {
                root = ((DOMSource) source).getNode();
            } else if (source instanceof SAXSource) {
                InputSource inSource = ((SAXSource) source).getInputSource();
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                dbf.setNamespaceAware(true);
                DocumentBuilder db = null;

                db = dbf.newDocumentBuilder();

                doc22 = db.parse(inSource);
                root = (Node) doc22.getDocumentElement();
            }

            XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");

            Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null),
                    Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)),
                    null, null);

            SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE,
                    (C14NMethodParameterSpec) null),
                    fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
                    Collections.singletonList(ref));

            // Load the KeyStore and get the signing key and certificate.
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(new FileInputStream("client_keystore.jks"), "changeit".toCharArray());
            KeyStore.PrivateKeyEntry keyEntry =
                    (KeyStore.PrivateKeyEntry) ks.getEntry("client", new KeyStore.PasswordProtection("changeit".toCharArray()));
            X509Certificate cert = (X509Certificate) keyEntry.getCertificate();
            // Create the KeyInfo containing the X509Data.
            KeyInfoFactory kif2 = fac.getKeyInfoFactory();
            List x509Content = new ArrayList();
            x509Content.add(cert.getSubjectX500Principal().getName());
            x509Content.add(cert);
            X509Data xd = kif2.newX509Data(x509Content);
            KeyInfo ki = kif2.newKeyInfo(Collections.singletonList(xd));

            Element header = getFirstChildElement(root/*.getDocumentElement()*/);
            DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), header /*doc.getDocumentElement()*/);

            XMLSignature signature = fac.newXMLSignature(si, ki);

            signature.sign(dsc);

            //TODO: change this to update the SOAP message, not write it to disks
            OutputStream os = new FileOutputStream("out.xml");
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer trans = tf.newTransformer();
            trans.transform(new DOMSource(root), new StreamResult(os));

        } catch (Exception ex) {
            System.out.println(ex);
        }
    }

    return true;
}

But I can't figure out how to update the SOAP request?

Brigidbrigida answered 29/9, 2011 at 13:50 Comment(5)
Does soapPart.setContent(new DOMSource(root)) not work? I'm just guessing, I've not done it myself.Disjoined
Unfortunately, this empties the bode and header elements. Thank you for looking, though!Brigidbrigida
Have you found a solution to this problem yet? I'm curious as I'm going to do something similarCousingerman
I dropped the idea, but I'm still interested in a solution if anyone has one!Brigidbrigida
My testing tells me that you do not have to do anything, since the signing already updates the SOAP message.Kiel
B
7

I develop a SOAPHandler for Xml Digital Signature of Soap Request.

public class SOAPSecurityHandler implements
        LogicalHandler<LogicalMessageContext> {

    static final String KEYSTORE_FILE = "keystore_name.jks";
    static final String KEYSTORE_INSTANCE = "JKS";
    static final String KEYSTORE_PWD = "123456";
    static final String KEYSTORE_ALIAS = "keystore";

    public Set<QName> getHeaders() {
        return Collections.emptySet();
    }

    @Override
    public boolean handleMessage(LogicalMessageContext smc) {
        Boolean outboundProperty = (Boolean) smc
                .get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

        try {

            if (outboundProperty) {

                Source source = smc.getMessage().getPayload();

                Node root = null;

                root = ((DOMSource) source).getNode();

                XMLSignatureFactory fac = XMLSignatureFactory
                        .getInstance("DOM");

                Reference ref = fac.newReference("", fac.newDigestMethod(
                        DigestMethod.SHA1, null), Collections.singletonList(fac
                        .newTransform(Transform.ENVELOPED,
                                (TransformParameterSpec) null)), null, null);

                SignedInfo si = fac.newSignedInfo(fac
                        .newCanonicalizationMethod(
                                CanonicalizationMethod.INCLUSIVE,
                                (C14NMethodParameterSpec) null), fac
                        .newSignatureMethod(SignatureMethod.RSA_SHA1, null),
                        Collections.singletonList(ref));

                // Load the KeyStore and get the signing key and certificate.
                KeyStore ks = KeyStore.getInstance(KEYSTORE_INSTANCE);
                ks.load(new FileInputStream(KEYSTORE_FILE),
                        KEYSTORE_PWD.toCharArray());
                KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) ks
                        .getEntry(
                                KEYSTORE_ALIAS,
                                new KeyStore.PasswordProtection(KEYSTORE_PWD
                                        .toCharArray()));
                X509Certificate cert = (X509Certificate) keyEntry
                        .getCertificate();
                // Create the KeyInfo containing the X509Data.
                KeyInfoFactory kif2 = fac.getKeyInfoFactory();
                List x509Content = new ArrayList();
                x509Content.add(cert.getSubjectX500Principal().getName());
                x509Content.add(cert);
                X509Data xd = kif2.newX509Data(x509Content);
                KeyInfo ki = kif2.newKeyInfo(Collections.singletonList(xd));

                Element header = DOMUtils.getFirstChildElement(root);
                DOMSignContext dsc = new DOMSignContext(
                        keyEntry.getPrivateKey(), header);

                XMLSignature signature = fac.newXMLSignature(si, ki);

                signature.sign(dsc);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return true;

    }

    public boolean handleFault(SOAPMessageContext smc) {
        // addDigitalSignature(smc);
        return true;
    }

    // nothing to clean up
    public void close(MessageContext messageContext) {
    }

    @Override
    public boolean handleFault(LogicalMessageContext arg0) {
        // TODO Auto-generated method stub
        return false;
    }

}

I think the problem in code of @AndrewBourgeois is the way of get Source.

Regards,

Baines answered 25/11, 2013 at 18:48 Comment(1)
Where is the logic for DomUtils?Gorham
C
6

The simplest way is to use functionality integrated in application server. For example :Securing JAX-WS Web services using message-level security with WebSphere App Server

How to configure signing on WAS you can find here.

And here is WebLogic documentation about Configuring Message-Level Security.

Calyces answered 27/12, 2011 at 12:25 Comment(3)
This is about signing, not general securing, which is well-understood. Maybe you could provide a more detailed link and/or example?Cousingerman
@LukasEder: message-level security refers to signing too. On this page you can find link to signing configuration too. I added it now to the response.Calyces
I didn't have the time to check this answer's contents, but did it solve the issue Lukas?Brigidbrigida
J
1

You can try soapPart.saveChanges();

Jabberwocky answered 27/1, 2016 at 9:15 Comment(0)
S
0

After the code line:

signature.sign(dsc);

insert this statement:

soapMsg.saveChanges();

It will save your changes.

Sting answered 28/1, 2016 at 8:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.