Example usage for javax.xml.soap SOAPMessage getSOAPHeader

List of usage examples for javax.xml.soap SOAPMessage getSOAPHeader

Introduction

In this page you can find the example usage for javax.xml.soap SOAPMessage getSOAPHeader.

Prototype

public SOAPHeader getSOAPHeader() throws SOAPException 

Source Link

Document

Gets the SOAP Header contained in this SOAPMessage object.

Usage

From source file:com.betfair.testing.utils.cougar.helpers.CougarHelpers.java

private void extractHeaderDataSOAP(SOAPMessage response, HttpResponseBean responseBean) throws SOAPException {
    //extract MimeHeaders
    MimeHeaders mime = response.getMimeHeaders();
    Iterator<MimeHeader> iter = mime.getAllHeaders();

    while (iter.hasNext()) {
        MimeHeader mimeH = iter.next();
        responseBean.addEntryToResponseHeaders(mimeH.getName(), mimeH.getValue());

    }//from   www .j a  v  a2  s .  c  o  m

    //extract SOAPHeaders from the envelope and a them to the mimeHeaders
    if (response.getSOAPHeader() != null) {
        javax.xml.soap.SOAPHeader header = response.getSOAPHeader();

        NodeList nodes = header.getChildNodes();

        for (int x = 0; x < nodes.getLength(); x++) {
            //if the header entry contains child nodes - write them with the node names
            if (nodes.item(x).hasChildNodes()) {
                NodeList childnodes = nodes.item(x).getChildNodes();
                for (int y = 0; y < childnodes.getLength(); y++) {
                    responseBean.addEntryToResponseHeaders(nodes.item(x).getLocalName(),
                            childnodes.item(y).getLocalName() + ":" + childnodes.item(y).getTextContent());
                }
            } else {
                responseBean.addEntryToResponseHeaders(nodes.item(x).getLocalName(),
                        nodes.item(x).getTextContent());
            }
        }
    }
}

From source file:io.hummer.util.ws.WebServiceClient.java

private SOAPMessage createSOAPMessage(Element request, List<Element> headers, String protocol)
        throws Exception {
    MessageFactory mf = MessageFactory.newInstance(protocol);
    SOAPMessage message = mf.createMessage();
    SOAPBody body = message.getSOAPBody();

    // check if we have a complete soap:Envelope as request..
    String ns = request.getNamespaceURI();
    if (request.getTagName().contains("Envelope")) {
        if (ns.equals("http://schemas.xmlsoap.org/soap/envelope/"))
            message = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL).createMessage(
                    new MimeHeaders(), new ByteArrayInputStream(xmlUtil.toString(request).getBytes()));
        if (ns.equals("http://www.w3.org/2003/05/soap-envelope"))
            message = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage(
                    new MimeHeaders(), new ByteArrayInputStream(xmlUtil.toString(request).getBytes()));

    } else {//from   w w w .j a  v a2 s .  c  om
        xmlUtil.appendChild(body, request);
    }
    for (Element h : headers) {
        xmlUtil.appendChild(message.getSOAPHeader(), h);
    }
    for (Element h : eprParamsAndProps) {
        xmlUtil.appendChild(message.getSOAPHeader(), h);
    }
    xmlUtil.appendChild(message.getSOAPHeader(), xmlUtil.toElement(
            "<wsa:To xmlns:wsa=\"" + EndpointReference.NS_WS_ADDRESSING + "\">" + endpointURL + "</wsa:To>"));
    message.saveChanges();
    return message;
}

From source file:org.keycloak.testsuite.adapter.servlet.SAMLServletAdapterTest.java

@Test
public void testInvalidCredentialsEcpFlow() throws Exception {
    Response authnRequestResponse = ClientBuilder.newClient().target(ecpSPPage.toString()).request()
            .header("Accept", "text/html; application/vnd.paos+xml")
            .header("PAOS", "ver='urn:liberty:paos:2003-08' ;'urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp'")
            .get();/* ww w  . j a v a 2 s  . co  m*/

    SOAPMessage authnRequestMessage = MessageFactory.newInstance().createMessage(null,
            new ByteArrayInputStream(authnRequestResponse.readEntity(byte[].class)));
    Iterator<SOAPHeaderElement> it = authnRequestMessage.getSOAPHeader()
            .<SOAPHeaderElement>getChildElements(new QName("urn:liberty:paos:2003-08", "Request"));

    it.next();

    it = authnRequestMessage.getSOAPHeader().<SOAPHeaderElement>getChildElements(
            new QName("urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp", "Request"));
    SOAPHeaderElement ecpRequestHeader = it.next();
    NodeList idpList = ecpRequestHeader.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:protocol",
            "IDPList");

    Assert.assertThat("No IDPList returned from Service Provider", idpList.getLength(), is(1));

    NodeList idpEntries = idpList.item(0).getChildNodes();

    Assert.assertThat("No IDPEntry returned from Service Provider", idpEntries.getLength(), is(1));

    String singleSignOnService = null;

    for (int i = 0; i < idpEntries.getLength(); i++) {
        Node item = idpEntries.item(i);
        NamedNodeMap attributes = item.getAttributes();
        Node location = attributes.getNamedItem("Loc");

        singleSignOnService = location.getNodeValue();
    }

    Assert.assertThat("Could not obtain SSO Service URL", singleSignOnService, notNullValue());

    Document authenticationRequest = authnRequestMessage.getSOAPBody().getFirstChild().getOwnerDocument();
    String username = "pedroigor";
    String password = "baspassword";
    String pair = username + ":" + password;
    String authHeader = "Basic " + Base64.encodeBytes(pair.getBytes());

    Response authenticationResponse = ClientBuilder.newClient().target(singleSignOnService).request()
            .header(HttpHeaders.AUTHORIZATION, authHeader)
            .post(Entity.entity(DocumentUtil.asString(authenticationRequest), "application/soap+xml"));

    Assert.assertThat(authenticationResponse.getStatus(), is(OK.getStatusCode()));

    SOAPMessage responseMessage = MessageFactory.newInstance().createMessage(null,
            new ByteArrayInputStream(authenticationResponse.readEntity(byte[].class)));
    Node samlResponse = responseMessage.getSOAPBody().getFirstChild();

    Assert.assertThat(samlResponse, notNullValue());

    StatusResponseType responseType = (StatusResponseType) SAMLParser.getInstance().parse(samlResponse);
    StatusCodeType statusCode = responseType.getStatus().getStatusCode();

    Assert.assertThat(statusCode.getStatusCode().getValue().toString(),
            is(not(JBossSAMLURIConstants.STATUS_SUCCESS.get())));
}

From source file:org.keycloak.testsuite.adapter.servlet.SAMLServletAdapterTest.java

@Test
public void testSuccessfulEcpFlow() throws Exception {
    Response authnRequestResponse = ClientBuilder.newClient().target(ecpSPPage.toString()).request()
            .header("Accept", "text/html; application/vnd.paos+xml")
            .header("PAOS", "ver='urn:liberty:paos:2003-08' ;'urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp'")
            .get();//from w w  w.  j a v  a 2  s.c  om

    SOAPMessage authnRequestMessage = MessageFactory.newInstance().createMessage(null,
            new ByteArrayInputStream(authnRequestResponse.readEntity(byte[].class)));

    //printDocument(authnRequestMessage.getSOAPPart().getContent(), System.out);

    Iterator<SOAPHeaderElement> it = authnRequestMessage.getSOAPHeader().<SOAPHeaderElement>getChildElements(
            new QName("urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp", "Request"));
    SOAPHeaderElement ecpRequestHeader = it.next();
    NodeList idpList = ecpRequestHeader.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:protocol",
            "IDPList");

    Assert.assertThat("No IDPList returned from Service Provider", idpList.getLength(), is(1));

    NodeList idpEntries = idpList.item(0).getChildNodes();

    Assert.assertThat("No IDPEntry returned from Service Provider", idpEntries.getLength(), is(1));

    String singleSignOnService = null;

    for (int i = 0; i < idpEntries.getLength(); i++) {
        Node item = idpEntries.item(i);
        NamedNodeMap attributes = item.getAttributes();
        Node location = attributes.getNamedItem("Loc");

        singleSignOnService = location.getNodeValue();
    }

    Assert.assertThat("Could not obtain SSO Service URL", singleSignOnService, notNullValue());

    Document authenticationRequest = authnRequestMessage.getSOAPBody().getFirstChild().getOwnerDocument();
    String username = "pedroigor";
    String password = "password";
    String pair = username + ":" + password;
    String authHeader = "Basic " + Base64.encodeBytes(pair.getBytes());

    Response authenticationResponse = ClientBuilder.newClient().target(singleSignOnService).request()
            .header(HttpHeaders.AUTHORIZATION, authHeader)
            .post(Entity.entity(DocumentUtil.asString(authenticationRequest), "text/xml"));

    Assert.assertThat(authenticationResponse.getStatus(), is(OK.getStatusCode()));

    SOAPMessage responseMessage = MessageFactory.newInstance().createMessage(null,
            new ByteArrayInputStream(authenticationResponse.readEntity(byte[].class)));

    //printDocument(responseMessage.getSOAPPart().getContent(), System.out);

    SOAPHeader responseMessageHeaders = responseMessage.getSOAPHeader();

    NodeList ecpResponse = responseMessageHeaders.getElementsByTagNameNS(
            JBossSAMLURIConstants.ECP_PROFILE.get(), JBossSAMLConstants.RESPONSE__ECP.get());

    Assert.assertThat("No ECP Response", ecpResponse.getLength(), is(1));

    Node samlResponse = responseMessage.getSOAPBody().getFirstChild();

    Assert.assertThat(samlResponse, notNullValue());

    ResponseType responseType = (ResponseType) SAMLParser.getInstance().parse(samlResponse);
    StatusCodeType statusCode = responseType.getStatus().getStatusCode();

    Assert.assertThat(statusCode.getValue().toString(), is(JBossSAMLURIConstants.STATUS_SUCCESS.get()));
    Assert.assertThat(responseType.getDestination(), is(ecpSPPage.toString() + "/"));
    Assert.assertThat(responseType.getSignature(), notNullValue());
    Assert.assertThat(responseType.getAssertions().size(), is(1));

    SOAPMessage samlResponseRequest = MessageFactory.newInstance().createMessage();

    samlResponseRequest.getSOAPBody().addDocument(responseMessage.getSOAPBody().extractContentAsDocument());

    ByteArrayOutputStream os = new ByteArrayOutputStream();

    samlResponseRequest.writeTo(os);

    Response serviceProviderFinalResponse = ClientBuilder.newClient().target(responseType.getDestination())
            .request().post(Entity.entity(os.toByteArray(), "application/vnd.paos+xml"));

    Map<String, NewCookie> cookies = serviceProviderFinalResponse.getCookies();

    Invocation.Builder resourceRequest = ClientBuilder.newClient().target(responseType.getDestination())
            .request();

    for (NewCookie cookie : cookies.values()) {
        resourceRequest.cookie(cookie);
    }

    Response resourceResponse = resourceRequest.get();
    Assert.assertThat(resourceResponse.readEntity(String.class), containsString("pedroigor"));
}

From source file:whitelabel.cloud.wsclient.WebServiceAuthenticator.java

public void authenticateInClear(final SOAPMessage request, final String username, final String password)
        throws WsAuthenticationException {

    if (request == null) {
        LOG.error(" SoapMessage request not defined");
        throw new WsAuthenticationException("SOAP_REQUEST_NOT_DEFINED");
    }/*from  w w  w  .  j a v  a2s . com*/
    if (username == null || password == null || username.trim().length() == 0
            || password.trim().length() == 0) {
        LOG.error("Username: " + username + " password: " + password + " - invalid parameters");
        throw new WsAuthenticationException("INVALID_PARAMETERS");
    }

    String nonceValue = generateNonceBase64(16);
    String createdValue = dfe.print(new Date());
    String userValue = username;
    String pwdValue = password;
    String pwdType = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText";

    QName securityQName = new QName(
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security",
            "wsse");
    QName usernameTokenQName = new QName(
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
            "UsernameToken", "wsse");
    QName usernameQName = new QName(
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Username",
            "wsse");
    QName PasswordQName = new QName(
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Password",
            "wsse");
    QName PasswordTypeQName = new QName("Type");
    QName nonceQName = new QName(
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Nonce",
            "wsse");
    QName createdQName = new QName(
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", "Created",
            "wsu");

    try {
        SOAPElement securitySoap = request.getSOAPHeader().addChildElement(securityQName);
        SOAPElement usernameTokenSoap = securitySoap.addChildElement(usernameTokenQName);
        SOAPElement usernameSoap = usernameTokenSoap.addChildElement(usernameQName);
        usernameSoap.addTextNode(userValue);
        SOAPElement passwordSoap = usernameTokenSoap.addChildElement(PasswordQName);
        passwordSoap.addTextNode(pwdValue);
        passwordSoap.addAttribute(PasswordTypeQName, pwdType);
        SOAPElement nonceSoap = usernameTokenSoap.addChildElement(nonceQName);
        nonceSoap.addTextNode(nonceValue);
        SOAPElement creadedSoap = usernameTokenSoap.addChildElement(createdQName);
        creadedSoap.addTextNode(createdValue);
    } catch (SOAPException se) {
        LOG.error(se);
        throw new WsAuthenticationException("SOAPHEADER_CREATION", se);
    }
}

From source file:whitelabel.cloud.wsclient.WebServiceAuthenticator.java

public void authenticateWithDigest(final SOAPMessage request, final String username, final String password)
        throws WsAuthenticationException {

    if (request == null) {
        LOG.error(" SoapMessage request not defined");
        throw new WsAuthenticationException("SOAP_REQUEST_NOT_DEFINED");
    }//from  w  w w  .j  a  v a 2 s  . c o m
    if (username == null || password == null || username.trim().length() == 0
            || password.trim().length() == 0) {
        LOG.error("Username: " + username + " password: " + password + " - invalid parameters");
        throw new WsAuthenticationException("INVALID_PARAMETERS");
    }

    String nonceValue = generateNonceBase64(16);
    String createdValue = dfe.print(new Date());
    String userValue = username;
    String pwdValue = crypthPassword(nonceValue, createdValue, password);

    String pwdType = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest";

    QName securityQName = new QName(
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security",
            "wsse");
    QName usernameTokenQName = new QName(
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
            "UsernameToken", "wsse");
    QName usernameQName = new QName(
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Username",
            "wsse");
    QName PasswordQName = new QName(
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Password",
            "wsse");
    QName PasswordTypeQName = new QName("Type");
    QName nonceQName = new QName(
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Nonce",
            "wsse");
    QName createdQName = new QName(
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", "Created",
            "wsu");

    SOAPElement securitySoap;
    try {
        securitySoap = request.getSOAPHeader().addChildElement(securityQName);
        SOAPElement usernameTokenSoap = securitySoap.addChildElement(usernameTokenQName);
        SOAPElement usernameSoap = usernameTokenSoap.addChildElement(usernameQName);
        usernameSoap.addTextNode(userValue);
        SOAPElement passwordSoap = usernameTokenSoap.addChildElement(PasswordQName);
        passwordSoap.addTextNode(pwdValue);
        passwordSoap.addAttribute(PasswordTypeQName, pwdType);
        SOAPElement nonceSoap = usernameTokenSoap.addChildElement(nonceQName);
        nonceSoap.addTextNode(nonceValue);
        SOAPElement creadedSoap = usernameTokenSoap.addChildElement(createdQName);
        creadedSoap.addTextNode(createdValue);
    } catch (SOAPException se) {
        LOG.error(se);
        throw new WsAuthenticationException("SOAPHEADER_CREATION", se);
    }
}

From source file:org.apache.hise.engine.jaxws.HISEJaxWSService.java

@Transactional
public SOAPMessage invoke(final SOAPMessage request) {
    try {//from  ww  w  . jav a  2  s. co m
        // TransactionStatus tx = transactionManager.getTransaction(new DefaultTransactionDefinition());
        //                    assert transactionManager.isValidateExistingTransaction();
        MessageContext c = context.getMessageContext();
        Object operationInfo = c.get("org.apache.cxf.service.model.OperationInfo");
        QName operation = (QName) operationInfo.getClass().getMethod("getName").invoke(operationInfo);
        QName portType = (QName) c.get("javax.xml.ws.wsdl.interface");
        QName operation2 = (QName) c.get("javax.xml.ws.wsdl.operation");

        Element body = request.getSOAPBody();
        __log.debug("invoking " + request + " operation:" + operation + " portType:" + portType + " operation2:"
                + operation2);
        Node approveResponseHeader = hiseEngine.receive(HISEJaxWSService.this, portType,
                operation.getLocalPart(), body, request.getSOAPHeader());
        SOAPMessage m = messageFactory.createMessage();

        Document doc = m.getSOAPHeader().getOwnerDocument();
        if (approveResponseHeader != null) {
            m.getSOAPHeader().appendChild(doc.importNode(approveResponseHeader, true));
        }
        return m;
    } catch (Exception e) {
        throw new RuntimeException("Error during receiving message ", e);
    }
}

From source file:org.apache.ws.scout.transport.SaajTransport.java

private SOAPMessage createSOAPMessage(Element elem) throws Exception {
    String prefix = "";
    MessageFactory msgFactory = MessageFactory.newInstance();
    SOAPFactory factory = SOAPFactory.newInstance();

    SOAPMessage message = msgFactory.createMessage();
    message.getSOAPHeader().detachNode();
    SOAPPart soapPart = message.getSOAPPart();
    SOAPBody soapBody = soapPart.getEnvelope().getBody();
    //Create the outer body element
    Name bodyName = factory.createName(elem.getNodeName(), prefix, UDDI_V2_NAMESPACE);
    SOAPBodyElement bodyElement = soapBody.addBodyElement(bodyName);
    bodyElement.addNamespaceDeclaration(prefix, UDDI_V2_NAMESPACE);
    appendAttributes(bodyElement, elem.getAttributes(), factory);
    appendElements(bodyElement, elem.getChildNodes(), factory);
    return message;
}

From source file:org.codice.ddf.security.interceptor.AnonymousInterceptor.java

@Override
public void handleMessage(SoapMessage message) throws Fault {

    if (anonymousAccessDenied) {
        LOGGER.debug("AnonymousAccess not enabled - no message checking performed.");
        return;/*from w  ww .  j ava  2s . co  m*/
    }

    if (message != null) {
        SoapVersion version = message.getVersion();
        SOAPMessage soapMessage = getSOAPMessage(message);
        SOAPFactory soapFactory = null;
        SOAPElement securityHeader = null;

        //Check if security header exists; if not, execute AnonymousInterceptor logic
        String actor = (String) getOption(WSHandlerConstants.ACTOR);
        if (actor == null) {
            actor = (String) message.getContextualProperty(SecurityConstants.ACTOR);
        }

        Element existingSecurityHeader = null;
        try {
            LOGGER.debug("Checking for security header.");
            existingSecurityHeader = WSSecurityUtil.getSecurityHeader(soapMessage.getSOAPPart(), actor);
        } catch (WSSecurityException e1) {
            LOGGER.debug("Issue with getting security header", e1);
        }
        if (existingSecurityHeader == null) {
            LOGGER.debug("Current request has no security header, continuing with AnonymousInterceptor");

            AssertionInfoMap assertionInfoMap = message.get(AssertionInfoMap.class);

            // if there is a policy we need to follow or we are ignoring policies, prepare the SOAP message
            if ((assertionInfoMap != null) || overrideEndpointPolicies) {
                RequestData reqData = new CXFRequestData();

                WSSConfig config = (WSSConfig) message.getContextualProperty(WSSConfig.class.getName());
                WSSecurityEngine engine = null;
                if (config != null) {
                    engine = new WSSecurityEngine();
                    engine.setWssConfig(config);
                }
                if (engine == null) {
                    engine = new WSSecurityEngine();
                    config = engine.getWssConfig();
                }

                reqData.setWssConfig(config);

                try {
                    soapFactory = SOAPFactory.newInstance();
                } catch (SOAPException e) {
                    LOGGER.error("Could not create a SOAPFactory.", e);
                    return; // can't add anything if we can't create it
                }
                if (soapFactory != null) {
                    //Create security header
                    try {
                        securityHeader = soapFactory.createElement(WSConstants.WSSE_LN, WSConstants.WSSE_PREFIX,
                                WSConstants.WSSE_NS);
                        securityHeader.addAttribute(
                                new QName(WSConstants.URI_SOAP11_ENV, WSConstants.ATTR_MUST_UNDERSTAND), "1");
                    } catch (SOAPException e) {
                        LOGGER.error("Unable to create security header for anonymous user.", e);
                        return; // can't create the security - just return
                    }
                }
            }

            EffectivePolicy effectivePolicy = message.get(EffectivePolicy.class);
            Exchange exchange = message.getExchange();
            BindingOperationInfo bindingOperationInfo = exchange.getBindingOperationInfo();
            Endpoint endpoint = exchange.get(Endpoint.class);
            if (null == endpoint) {
                return;
            }
            EndpointInfo endpointInfo = endpoint.getEndpointInfo();

            Bus bus = exchange.get(Bus.class);
            PolicyEngine policyEngine = bus.getExtension(PolicyEngine.class);

            if (effectivePolicy == null) {
                if (policyEngine != null) {
                    if (MessageUtils.isRequestor(message)) {
                        effectivePolicy = policyEngine.getEffectiveClientResponsePolicy(endpointInfo,
                                bindingOperationInfo, message);
                    } else {
                        effectivePolicy = policyEngine.getEffectiveServerRequestPolicy(endpointInfo,
                                bindingOperationInfo, message);
                    }
                }
            }

            //Auto analyze endpoint policies

            //Token Assertions
            String tokenAssertion = null;
            String tokenType = null;

            //Security Binding Assertions
            boolean layoutLax = false;
            boolean layoutStrict = false;
            boolean layoutLaxTimestampFirst = false;
            boolean layoutLaxTimestampLast = false;
            boolean requireClientCert = false;
            QName secBindingAssertion = null;

            //Supporting Token Assertions
            QName supportingTokenAssertion = null;
            boolean policyRequirementsSupported = false;

            // if there is a policy, try to follow it as closely as possible
            if (effectivePolicy != null) {
                Policy policy = effectivePolicy.getPolicy();
                if (policy != null) {
                    AssertionInfoMap infoMap = new AssertionInfoMap(policy);
                    Set<Map.Entry<QName, Collection<AssertionInfo>>> entries = infoMap.entrySet();
                    for (Map.Entry<QName, Collection<AssertionInfo>> entry : entries) {
                        Collection<AssertionInfo> assetInfoList = entry.getValue();
                        for (AssertionInfo info : assetInfoList) {
                            LOGGER.debug("Assertion Name: {}", info.getAssertion().getName().getLocalPart());
                            QName qName = info.getAssertion().getName();
                            StringWriter out = new StringWriter();
                            XMLStreamWriter writer = null;
                            try {
                                writer = XMLOutputFactory.newInstance().createXMLStreamWriter(out);
                            } catch (XMLStreamException e) {
                                LOGGER.debug("Error with XMLStreamWriter", e);
                            } catch (FactoryConfigurationError e) {
                                LOGGER.debug("Error with FactoryConfiguration", e);
                            }
                            try {
                                if (writer != null) {
                                    info.getAssertion().serialize(writer);
                                    writer.flush();
                                }
                            } catch (XMLStreamException e) {
                                LOGGER.debug("Error with XMLStream", e);
                            } finally {
                                if (writer != null) {
                                    try {
                                        writer.close();
                                    } catch (XMLStreamException ignore) {
                                        //ignore
                                    }
                                }
                            }
                            LOGGER.trace("Assertion XML: {}", out.toString());
                            String xml = out.toString();

                            // TODO DDF-1205 complete support for dynamic policy handling
                            if (qName.equals(SP12Constants.TRANSPORT_BINDING)) {
                                secBindingAssertion = qName;
                            } else if (qName.equals(SP12Constants.INCLUDE_TIMESTAMP)) {
                                createIncludeTimestamp(soapFactory, securityHeader);
                            } else if (qName.equals(SP12Constants.LAYOUT)) {
                                String xpathLax = "/Layout/Policy/Lax";
                                String xpathStrict = "/Layout/Policy/Strict";
                                String xpathLaxTimestampFirst = "/Layout/Policy/LaxTimestampFirst";
                                String xpathLaxTimestampLast = "/Layout/Policy/LaxTimestampLast";

                            } else if (qName.equals(SP12Constants.TRANSPORT_TOKEN)) {

                            } else if (qName.equals(SP12Constants.HTTPS_TOKEN)) {
                                String xpath = "/HttpsToken/Policy/RequireClientCertificate";

                            } else if (qName.equals(SP12Constants.SIGNED_SUPPORTING_TOKENS)) {
                                String xpath = "/SignedSupportingTokens/Policy//IssuedToken/RequestSecurityTokenTemplate/TokenType";
                                tokenType = retrieveXmlValue(xml, xpath);
                                supportingTokenAssertion = qName;

                            } else if (qName.equals(SP12Constants.SUPPORTING_TOKENS)) {
                                String xpath = "/SupportingTokens/Policy//IssuedToken/RequestSecurityTokenTemplate/TokenType";
                                tokenType = retrieveXmlValue(xml, xpath);
                                supportingTokenAssertion = qName;

                            } else if (qName.equals(
                                    org.apache.cxf.ws.addressing.policy.MetadataConstants.ADDRESSING_ASSERTION_QNAME)) {
                                createAddressing(message, soapMessage, soapFactory);

                            } else if (qName.equals(SP12Constants.TRUST_13)) {

                            } else if (qName.equals(SP12Constants.ISSUED_TOKEN)) {
                                //Check Token Assertion
                                String xpath = "/IssuedToken/@IncludeToken";
                                tokenAssertion = retrieveXmlValue(xml, xpath);

                            } else if (qName.equals(SP12Constants.WSS11)) {

                            }
                        }
                    }

                    //Check security and token policies
                    if (tokenAssertion != null && tokenType != null
                            && tokenAssertion.trim().equals(SP12Constants.INCLUDE_ALWAYS_TO_RECIPIENT)
                            && tokenType.trim().equals(TOKEN_SAML20)) {
                        policyRequirementsSupported = true;
                    } else {
                        LOGGER.warn(
                                "AnonymousInterceptor does not support the policies presented by the endpoint.");
                    }

                } else {
                    if (overrideEndpointPolicies) {
                        LOGGER.debug(
                                "WS Policy is null, override is true - an anonymous assertion will be generated");
                    } else {
                        LOGGER.warn(
                                "WS Policy is null, override flag is false - no anonymous assertion will be generated.");
                    }
                }
            } else {
                if (overrideEndpointPolicies) {
                    LOGGER.debug(
                            "Effective WS Policy is null, override is true - an anonymous assertion will be generated");
                } else {
                    LOGGER.warn(
                            "Effective WS Policy is null, override flag is false - no anonymous assertion will be generated.");
                }
            }

            if (policyRequirementsSupported || overrideEndpointPolicies) {
                LOGGER.debug("Creating anonymous security token.");
                if (soapFactory != null) {
                    HttpServletRequest request = (HttpServletRequest) message
                            .get(AbstractHTTPDestination.HTTP_REQUEST);
                    createSecurityToken(version, soapFactory, securityHeader, request.getRemoteAddr());
                    try {
                        // Add security header to SOAP message
                        soapMessage.getSOAPHeader().addChildElement(securityHeader);
                    } catch (SOAPException e) {
                        LOGGER.error("Issue when adding security header to SOAP message:" + e.getMessage());
                    }
                } else {
                    LOGGER.debug("Security Header was null so not creating a SAML Assertion");
                }
            }
        } else {
            LOGGER.debug("SOAP message contains security header, no action taken by the AnonymousInterceptor.");
        }
        if (LOGGER.isTraceEnabled()) {
            try {
                LOGGER.trace("SOAP request after anonymous interceptor: {}",
                        SecurityLogger.getFormattedXml(soapMessage.getSOAPHeader().getParentNode()));
            } catch (SOAPException e) {
                //ignore
            }
        }
    } else {
        LOGGER.error("Incoming SOAP message is null - anonymous interceptor makes no sense.");
    }
}

From source file:org.codice.ddf.security.interceptor.AnonymousInterceptor.java

private void createAddressing(SoapMessage message, SOAPMessage soapMessage, SOAPFactory soapFactory) {

    String addressingProperty = org.apache.cxf.ws.addressing.JAXWSAConstants.CLIENT_ADDRESSING_PROPERTIES_INBOUND;
    AddressingProperties addressingProperties = new AddressingProperties();
    SOAPElement action = null;/*from w w  w .  j  a  va2 s.c o m*/

    try {
        action = soapFactory.createElement(org.apache.cxf.ws.addressing.Names.WSA_ACTION_NAME,
                org.apache.cxf.ws.addressing.JAXWSAConstants.WSA_PREFIX,
                org.apache.cxf.ws.security.wss4j.DefaultCryptoCoverageChecker.WSA_NS);
        action.addTextNode((String) message.get(org.apache.cxf.message.Message.REQUEST_URL));
        AttributedURIType attributedString = new AttributedURIType();
        String actionValue = StringUtils.defaultIfEmpty((String) message.get(SoapBindingConstants.SOAP_ACTION),
                "");
        attributedString.setValue(actionValue);
        addressingProperties.setAction(attributedString);
    } catch (SOAPException e) {
        LOGGER.error("Unable to add addressing action.", e);
    }

    SOAPElement messageId = null;
    try {
        messageId = soapFactory.createElement(org.apache.cxf.ws.addressing.Names.WSA_MESSAGEID_NAME,
                org.apache.cxf.ws.addressing.JAXWSAConstants.WSA_PREFIX,
                org.apache.cxf.ws.security.wss4j.DefaultCryptoCoverageChecker.WSA_NS);
        String uuid = "urn:uuid:" + UUID.randomUUID().toString();
        messageId.addTextNode(uuid);
        AttributedURIType attributedString = new AttributedURIType();
        attributedString.setValue(uuid);
        addressingProperties.setMessageID(attributedString);
    } catch (SOAPException e) {
        LOGGER.error("Unable to add addressing action.", e);
    }

    SOAPElement to = null;
    try {
        to = soapFactory.createElement(org.apache.cxf.ws.addressing.Names.WSA_TO_NAME,
                org.apache.cxf.ws.addressing.JAXWSAConstants.WSA_PREFIX,
                org.apache.cxf.ws.security.wss4j.DefaultCryptoCoverageChecker.WSA_NS);
        to.addTextNode((String) message.get(org.apache.cxf.message.Message.REQUEST_URL));
        EndpointReferenceType endpointReferenceType = new EndpointReferenceType();
        AttributedURIType attributedString = new AttributedURIType();
        attributedString.setValue((String) message.get(org.apache.cxf.message.Message.REQUEST_URL));
        endpointReferenceType.setAddress(attributedString);
        addressingProperties.setTo(endpointReferenceType);
    } catch (SOAPException e) {
        LOGGER.error("Unable to add addressing action.", e);
    }

    SOAPElement replyTo = null;
    try {
        replyTo = soapFactory.createElement(org.apache.cxf.ws.addressing.Names.WSA_REPLYTO_NAME,
                org.apache.cxf.ws.addressing.JAXWSAConstants.WSA_PREFIX,
                org.apache.cxf.ws.security.wss4j.DefaultCryptoCoverageChecker.WSA_NS);
        SOAPElement address = soapFactory.createElement(org.apache.cxf.ws.addressing.Names.WSA_ADDRESS_NAME,
                org.apache.cxf.ws.addressing.JAXWSAConstants.WSA_PREFIX,
                org.apache.cxf.ws.security.wss4j.DefaultCryptoCoverageChecker.WSA_NS);
        address.addTextNode(org.apache.cxf.ws.addressing.Names.WSA_ANONYMOUS_ADDRESS);
        replyTo.addChildElement(address);

        soapMessage.getSOAPHeader().addChildElement(messageId);
        soapMessage.getSOAPHeader().addChildElement(action);
        soapMessage.getSOAPHeader().addChildElement(to);
        soapMessage.getSOAPHeader().addChildElement(replyTo);
        message.put(addressingProperty, addressingProperties);
    } catch (SOAPException e) {
        LOGGER.error("Unable to add addressing action.", e);
    }
}