Search in sources :

Example 11 with SOAPPart

use of javax.xml.soap.SOAPPart in project ddf by codice.

the class AssertionConsumerService method processSoapResponse.

@POST
@Consumes({ "text/xml", "application/soap+xml" })
public Response processSoapResponse(InputStream body, @Context HttpServletRequest request) {
    try {
        SOAPPart soapMessage = SamlProtocol.parseSoapMessage(IOUtils.toString(body));
        String relayState = getRelayState(soapMessage);
        org.opensaml.saml.saml2.core.Response samlpResponse = getSamlpResponse(soapMessage);
        boolean validateResponse = validateResponse(samlpResponse, false);
        if (validateResponse) {
            return processSamlResponse(samlpResponse, relayState, false);
        }
    } catch (XMLStreamException e) {
        LOGGER.debug("Unable to parse SOAP message from response.", e);
    } catch (IOException e) {
        LOGGER.debug("Unable to get SAMLP response.", e);
    } catch (SOAPException e) {
        LOGGER.debug("Unable to get relay state from response.", e);
    }
    return Response.serverError().entity("Invalid AuthN response.").build();
}
Also used : XMLStreamException(javax.xml.stream.XMLStreamException) SOAPException(javax.xml.soap.SOAPException) SOAPPart(javax.xml.soap.SOAPPart) IOException(java.io.IOException) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 12 with SOAPPart

use of javax.xml.soap.SOAPPart in project ddf by codice.

the class LogoutRequestService method soapLogoutRequest.

@POST
@Consumes({ "text/xml", "application/soap+xml" })
public Response soapLogoutRequest(InputStream body, @Context HttpServletRequest request) {
    XMLObject xmlObject;
    try {
        String bodyString = IOUtils.toString(body, StandardCharsets.UTF_8);
        SOAPPart soapMessage = SamlProtocol.parseSoapMessage(bodyString);
        xmlObject = SamlProtocol.getXmlObjectFromNode(soapMessage.getEnvelope().getBody().getFirstChild());
        if (!(xmlObject instanceof LogoutRequest)) {
            LOGGER.info(UNABLE_TO_PARSE_LOGOUT_REQUEST);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Type of object is {}", xmlObject == null ? "null" : xmlObject.getSchemaType());
            }
            return Response.serverError().build();
        }
    } catch (SOAPException | XMLStreamException | IOException | WSSecurityException e) {
        LOGGER.debug("Error parsing input", e);
        return Response.serverError().build();
    }
    LogoutRequest logoutRequest = (LogoutRequest) xmlObject;
    if (logoutMessage == null) {
        LOGGER.info("Logout message not available yet");
        return Response.serverError().build();
    }
    // Pre-build response with success status
    LogoutWrapper<LogoutResponse> logoutResponse = logoutMessage.buildLogoutResponse(logoutRequest.getIssuer().getValue(), StatusCode.SUCCESS, logoutRequest.getID());
    try {
        if (!validateSignature(logoutRequest)) {
            return getSamlpSoapLogoutResponse(logoutResponse, StatusCode.AUTHN_FAILED, null);
        }
        new SamlValidator.Builder(simpleSign).buildAndValidate(this.request.getRequestURL().toString(), SamlProtocol.Binding.HTTP_POST, logoutRequest);
        httpSessionInvalidator.invalidateSession(logoutRequest.getNameID().getValue(), this::extractSubject);
        securityLogger.audit("Subject logged out by backchannel request: {}", logoutRequest.getNameID().getValue());
        return getSamlpSoapLogoutResponse(logoutResponse);
    } catch (ValidationException e) {
        LOGGER.info(UNABLE_TO_VALIDATE_LOGOUT_REQUEST, e);
        return getSamlpSoapLogoutResponse(logoutResponse, StatusCode.RESPONDER, e.getMessage());
    }
}
Also used : ValidationException(ddf.security.samlp.impl.ValidationException) LogoutResponse(org.opensaml.saml.saml2.core.LogoutResponse) SignableXMLObject(org.opensaml.xmlsec.signature.SignableXMLObject) XMLObject(org.opensaml.core.xml.XMLObject) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException) XMLStreamException(javax.xml.stream.XMLStreamException) SOAPException(javax.xml.soap.SOAPException) SamlValidator(ddf.security.samlp.impl.SamlValidator) SOAPPart(javax.xml.soap.SOAPPart) LogoutRequest(org.opensaml.saml.saml2.core.LogoutRequest) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 13 with SOAPPart

use of javax.xml.soap.SOAPPart in project ddf by codice.

the class PaosInInterceptor method handleMessage.

@Override
public void handleMessage(Message message) throws Fault {
    List authHeader = (List) ((Map) message.getExchange().getOutMessage().get(Message.PROTOCOL_HEADERS)).get("Authorization");
    String authorization = null;
    if (authHeader != null && authHeader.size() > 0) {
        authorization = (String) authHeader.get(0);
    }
    InputStream content = message.getContent(InputStream.class);
    String contentType = (String) message.get(Message.CONTENT_TYPE);
    if (contentType == null || !contentType.contains(APPLICATION_VND_PAOS_XML)) {
        return;
    }
    try {
        SOAPPart soapMessage = SamlProtocol.parseSoapMessage(IOUtils.toString(content, StandardCharsets.UTF_8));
        Iterator iterator = soapMessage.getEnvelope().getHeader().examineAllHeaderElements();
        IDPEntry idpEntry = null;
        String relayState = "";
        String responseConsumerURL = "";
        String messageId = "";
        while (iterator.hasNext()) {
            Element soapHeaderElement = (SOAPHeaderElement) iterator.next();
            if (RELAY_STATE.equals(soapHeaderElement.getLocalName())) {
                relayState = DOM2Writer.nodeToString(soapHeaderElement);
            } else if (REQUEST.equals(soapHeaderElement.getLocalName()) && soapHeaderElement.getNamespaceURI().equals(URN_OASIS_NAMES_TC_SAML_2_0_PROFILES_SSO_ECP)) {
                try {
                    soapHeaderElement = SamlProtocol.convertDomImplementation(soapHeaderElement);
                    Request ecpRequest = (Request) OpenSAMLUtil.fromDom(soapHeaderElement);
                    IDPList idpList = ecpRequest.getIDPList();
                    if (idpList == null) {
                        throw new Fault(new AccessDeniedException(IDP_SERVER_FAILURE_MSG));
                    }
                    List<IDPEntry> idpEntrys = idpList.getIDPEntrys();
                    if (idpEntrys == null || idpEntrys.size() == 0) {
                        throw new Fault(new AccessDeniedException(IDP_SERVER_FAILURE_MSG));
                    }
                    // choose the right entry, probably need to do something better than select the first
                    // one
                    // but the spec doesn't specify how this is supposed to be done
                    idpEntry = idpEntrys.get(0);
                } catch (WSSecurityException e) {
                    // TODO figure out IdP alternatively
                    LOGGER.info("Unable to determine IdP appropriately. ECP connection will fail. SP may be incorrectly configured. Contact the administrator for the remote system.");
                }
            } else if (REQUEST.equals(soapHeaderElement.getLocalName()) && soapHeaderElement.getNamespaceURI().equals(URN_LIBERTY_PAOS_2003_08)) {
                responseConsumerURL = soapHeaderElement.getAttribute(RESPONSE_CONSUMER_URL);
                messageId = soapHeaderElement.getAttribute(MESSAGE_ID);
            }
        }
        if (idpEntry == null) {
            throw new Fault(new AccessDeniedException(IDP_SERVER_FAILURE_MSG));
        }
        String token = createToken(authorization);
        checkAuthnRequest(soapMessage);
        Element authnRequestElement = SamlProtocol.getDomElement(soapMessage.getEnvelope().getBody().getFirstChild());
        String loc = idpEntry.getLoc();
        String soapRequest = buildSoapMessage(token, relayState, authnRequestElement, null);
        HttpResponseWrapper httpResponse = getHttpResponse(loc, soapRequest, null);
        InputStream httpResponseContent = httpResponse.content;
        SOAPPart idpSoapResponse = SamlProtocol.parseSoapMessage(IOUtils.toString(httpResponseContent, StandardCharsets.UTF_8));
        Iterator responseHeaderElements = idpSoapResponse.getEnvelope().getHeader().examineAllHeaderElements();
        String newRelayState = "";
        while (responseHeaderElements.hasNext()) {
            SOAPHeaderElement soapHeaderElement = (SOAPHeaderElement) responseHeaderElements.next();
            if (RESPONSE.equals(soapHeaderElement.getLocalName())) {
                String assertionConsumerServiceURL = soapHeaderElement.getAttribute(ASSERTION_CONSUMER_SERVICE_URL);
                if (!responseConsumerURL.equals(assertionConsumerServiceURL)) {
                    String soapFault = buildSoapFault(ECP_RESPONSE, "The responseConsumerURL does not match the assertionConsumerServiceURL.");
                    httpResponse = getHttpResponse(responseConsumerURL, soapFault, null);
                    message.setContent(InputStream.class, httpResponse.content);
                    return;
                }
            } else if (RELAY_STATE.equals(soapHeaderElement.getLocalName())) {
                newRelayState = DOM2Writer.nodeToString(soapHeaderElement);
                if (StringUtils.isNotEmpty(relayState) && !relayState.equals(newRelayState)) {
                    LOGGER.debug("RelayState does not match between ECP request and response");
                }
                if (StringUtils.isNotEmpty(relayState)) {
                    newRelayState = relayState;
                }
            }
        }
        checkSamlpResponse(idpSoapResponse);
        Element samlpResponseElement = SamlProtocol.getDomElement(idpSoapResponse.getEnvelope().getBody().getFirstChild());
        XMLObject paosResponse = null;
        if (StringUtils.isNotEmpty(messageId)) {
            paosResponse = getPaosResponse(messageId);
        }
        String soapResponse = buildSoapMessage(null, newRelayState, samlpResponseElement, paosResponse);
        httpResponse = getHttpResponse(responseConsumerURL, soapResponse, message.getExchange().getOutMessage());
        if (httpResponse.statusCode < 400) {
            httpResponseContent = httpResponse.content;
            message.setContent(InputStream.class, httpResponseContent);
            Map<String, List<String>> headers = new HashMap<>();
            message.put(Message.PROTOCOL_HEADERS, headers);
            httpResponse.headers.forEach((entry) -> headers.put(entry.getKey(), // CXF Expects pairs of <String, List<String>>
            entry.getValue() instanceof List ? ((List<Object>) entry.getValue()).stream().map(String::valueOf).collect(Collectors.toList()) : Lists.newArrayList(String.valueOf(entry.getValue()))));
        } else {
            throw new Fault(new AccessDeniedException("Unable to complete SAML ECP connection due to an error."));
        }
    } catch (IOException e) {
        LOGGER.debug("Error encountered while performing ECP handshake.", e);
    } catch (XMLStreamException | SOAPException e) {
        throw new Fault(new AccessDeniedException("Unable to complete SAML ECP connection. The server's response was not in the correct format."));
    } catch (WSSecurityException e) {
        throw new Fault(new AccessDeniedException("Unable to complete SAML ECP connection. Unable to send SOAP request messages."));
    }
}
Also used : SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) AccessDeniedException(org.apache.cxf.interceptor.security.AccessDeniedException) HashMap(java.util.HashMap) InputStream(java.io.InputStream) SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) Element(org.w3c.dom.Element) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) Request(org.opensaml.saml.saml2.ecp.Request) HttpRequest(com.google.api.client.http.HttpRequest) IDPList(org.opensaml.saml.saml2.core.IDPList) XMLObject(org.opensaml.core.xml.XMLObject) Fault(org.apache.cxf.interceptor.Fault) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException) XMLStreamException(javax.xml.stream.XMLStreamException) SOAPException(javax.xml.soap.SOAPException) SOAPPart(javax.xml.soap.SOAPPart) Iterator(java.util.Iterator) IDPList(org.opensaml.saml.saml2.core.IDPList) List(java.util.List) XMLObject(org.opensaml.core.xml.XMLObject) IDPEntry(org.opensaml.saml.saml2.core.IDPEntry)

Example 14 with SOAPPart

use of javax.xml.soap.SOAPPart in project Payara by payara.

the class WebServicesDelegateImpl method getName.

private Name getName(SOAPMessage message) {
    Name rvalue = null;
    SOAPPart soap = message.getSOAPPart();
    if (soap != null) {
        try {
            SOAPEnvelope envelope = soap.getEnvelope();
            if (envelope != null) {
                SOAPBody body = envelope.getBody();
                if (body != null) {
                    Iterator it = body.getChildElements();
                    while (it.hasNext()) {
                        Object o = it.next();
                        if (o instanceof SOAPElement) {
                            rvalue = ((SOAPElement) o).getElementName();
                            break;
                        }
                    }
                }
            }
        } catch (SOAPException se) {
            if (_logger.isLoggable(Level.FINE)) {
                _logger.log(Level.FINE, "WSS: Unable to get SOAP envelope", se);
            }
        }
    }
    return rvalue;
}
Also used : SOAPBody(javax.xml.soap.SOAPBody) SOAPException(javax.xml.soap.SOAPException) SOAPPart(javax.xml.soap.SOAPPart) Iterator(java.util.Iterator) SOAPElement(javax.xml.soap.SOAPElement) SOAPEnvelope(javax.xml.soap.SOAPEnvelope) Name(javax.xml.soap.Name) QName(javax.xml.namespace.QName)

Example 15 with SOAPPart

use of javax.xml.soap.SOAPPart in project jaffa-framework by jaffa-projects.

the class WebServiceInvoker method createSOAPMessage.

/**
 * Generate SOAPMessage based on the input arguments.
 * <p>
 * For example:
 *   <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:j="http://product1.mirotechnologies.com/material/core/StockBalanceFinder">
 *     <SOAP-ENV:Header/>
 *     <SOAP-ENV:Body>
 *       <j:performInquiry>
 *         <arg0>
 *           <part><operator>Equals</operator><values>P1000</values></part>
 *         </arg0>
 *       </j:performInquiry>
 *     </SOAP-ENV:Body>
 *   </SOAP-ENV:Envelope>
 * @param arguments the arguments for the WebService.
 * @return a SOAPMessage.
 * @throws SOAPException if any SOAP error occurs.
 * @throws JAXBException if any XML (un)marshalling error occurs.
 */
protected SOAPMessage createSOAPMessage(Object... arguments) throws SOAPException, JAXBException {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage message = messageFactory.createMessage();
    SOAPPart messagePart = message.getSOAPPart();
    SOAPEnvelope envelope = messagePart.getEnvelope();
    String tns = this.obtainTargetNamespace();
    if (tns != null) {
        envelope.addNamespaceDeclaration(CUSTOM_PREFIX, tns);
    }
    SOAPBody body = message.getSOAPBody();
    SOAPElement operationElement = tns != null ? body.addBodyElement(envelope.createQName(getOperationName(), CUSTOM_PREFIX)) : body.addBodyElement(envelope.createName(getOperationName()));
    // Add authentication
    addAuthorization(message);
    // An arg{i} node will be created for each argument
    if (arguments != null) {
        Annotation[][] parameterAnnotations = null;
        for (Method m : getWebServiceClass().getMethods()) {
            if (m.getName().equals(getOperationName()) && m.getAnnotation(WebMethod.class) != null) {
                parameterAnnotations = m.getParameterAnnotations();
            }
        }
        for (int i = 0; i < arguments.length; i++) {
            Object argument = arguments[i];
            Class argumentClass = argument.getClass();
            String webParamName = null;
            if (parameterAnnotations != null && parameterAnnotations.length > 0) {
                for (Annotation[] annotations : parameterAnnotations) {
                    for (Annotation annotation : annotations) {
                        if (annotation instanceof WebParam) {
                            WebParam webParam = (WebParam) annotation;
                            webParamName = webParam.name();
                            if (log.isDebugEnabled()) {
                                log.debug("webParamName :" + webParamName);
                            }
                        }
                    }
                }
            }
            if (Collection.class.isAssignableFrom(argumentClass)) {
                JAXBContext jc = null;
                Marshaller marshaller = null;
                List list = (List) argument;
                for (Object arrayElement : list) {
                    if (jc == null) {
                        jc = JAXBHelper.obtainJAXBContext(arrayElement.getClass());
                        marshaller = jc.createMarshaller();
                    }
                    if (webParamName != null) {
                        marshaller.marshal(new JAXBElement(new QName(webParamName), arrayElement.getClass(), arrayElement), operationElement);
                    } else {
                        marshaller.marshal(new JAXBElement(new QName("arg0"), arrayElement.getClass(), arrayElement), operationElement);
                    }
                }
            } else if (argumentClass.isArray()) {
                argumentClass = argumentClass.getComponentType();
                JAXBContext jc = JAXBHelper.obtainJAXBContext(argumentClass);
                Marshaller marshaller = jc.createMarshaller();
                for (int j = 0, len = Array.getLength(argument); j < len; j++) {
                    Object arrayElement = Array.get(argument, j);
                    if (webParamName != null) {
                        marshaller.marshal(new JAXBElement(new QName(webParamName), argumentClass, arrayElement), operationElement);
                    } else {
                        marshaller.marshal(new JAXBElement(new QName("arg0"), argumentClass, arrayElement), operationElement);
                    }
                }
            } else {
                JAXBContext jc = JAXBHelper.obtainJAXBContext(argumentClass);
                Marshaller marshaller = jc.createMarshaller();
                if (webParamName != null) {
                    marshaller.marshal(new JAXBElement(new QName(webParamName), argumentClass, argument), operationElement);
                } else {
                    marshaller.marshal(new JAXBElement(new QName("arg0"), argumentClass, argument), operationElement);
                }
            }
        }
    }
    // Save all changes to the Message
    message.saveChanges();
    if (log.isDebugEnabled()) {
        log.debug("Created SOAPMessage: " + message);
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            message.writeTo(os);
            log.debug("Contents of SOAPMessage: " + os.toString());
        } catch (Exception e) {
        // do nothing
        }
    }
    return message;
}
Also used : Marshaller(javax.xml.bind.Marshaller) MessageFactory(javax.xml.soap.MessageFactory) QName(javax.xml.namespace.QName) JAXBContext(javax.xml.bind.JAXBContext) SOAPEnvelope(javax.xml.soap.SOAPEnvelope) Method(java.lang.reflect.Method) WebMethod(javax.jws.WebMethod) JAXBElement(javax.xml.bind.JAXBElement) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SOAPMessage(javax.xml.soap.SOAPMessage) Annotation(java.lang.annotation.Annotation) SOAPException(javax.xml.soap.SOAPException) JAXBException(javax.xml.bind.JAXBException) SOAPFaultException(javax.xml.ws.soap.SOAPFaultException) SOAPBody(javax.xml.soap.SOAPBody) WebParam(javax.jws.WebParam) SOAPPart(javax.xml.soap.SOAPPart) SOAPElement(javax.xml.soap.SOAPElement) NodeList(org.w3c.dom.NodeList) List(java.util.List)

Aggregations

SOAPPart (javax.xml.soap.SOAPPart)45 SOAPMessage (javax.xml.soap.SOAPMessage)30 SOAPBody (javax.xml.soap.SOAPBody)28 SOAPEnvelope (javax.xml.soap.SOAPEnvelope)26 SOAPException (javax.xml.soap.SOAPException)26 MessageFactory (javax.xml.soap.MessageFactory)17 SOAPElement (javax.xml.soap.SOAPElement)14 Iterator (java.util.Iterator)13 Element (org.w3c.dom.Element)13 StreamSource (javax.xml.transform.stream.StreamSource)12 QName (javax.xml.namespace.QName)11 IOException (java.io.IOException)10 InputStream (java.io.InputStream)10 Name (javax.xml.soap.Name)10 NodeList (org.w3c.dom.NodeList)9 BufferedWriter (java.io.BufferedWriter)7 ByteArrayInputStream (java.io.ByteArrayInputStream)7 OutputStreamWriter (java.io.OutputStreamWriter)7 HttpURLConnection (java.net.HttpURLConnection)7 SOAPHeader (javax.xml.soap.SOAPHeader)6