Java Code Examples for org.apache.cxf.helpers.domutils#newDocument()

The following examples show how to use org.apache.cxf.helpers.domutils#newDocument() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StaxUtilsTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testCXF2468() throws Exception {
    Document doc = DOMUtils.newDocument();
    doc.appendChild(doc.createElementNS("http://blah.org/", "blah"));
    Element foo = doc.createElementNS("http://blah.org/", "foo");
    Attr attr = doc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:nil");
    attr.setValue("true");
    foo.setAttributeNodeNS(attr);
    doc.getDocumentElement().appendChild(foo);
    XMLStreamReader sreader = StaxUtils.createXMLStreamReader(doc);
    StringWriter sw = new StringWriter();
    XMLStreamWriter swriter = StaxUtils.createXMLStreamWriter(sw);
    StaxUtils.copy(sreader, swriter, true);
    swriter.flush();
    assertTrue("No xsi namespace: " + sw.toString(), sw.toString().contains("XMLSchema-instance"));
}
 
Example 2
Source File: SamlHeaderOutInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    try {
        SamlAssertionWrapper assertionWrapper = createAssertion(message);

        Document doc = DOMUtils.newDocument();
        Element assertionElement = assertionWrapper.toDOM(doc);
        String encodedToken = encodeToken(DOM2Writer.nodeToString(assertionElement));

        Map<String, List<String>> headers = getHeaders(message);

        StringBuilder builder = new StringBuilder();
        builder.append("SAML").append(' ').append(encodedToken);
        headers.put("Authorization",
            CastUtils.cast(Collections.singletonList(builder.toString()), String.class));

    } catch (Exception ex) {
        StringWriter sw = new StringWriter();
        ex.printStackTrace(new PrintWriter(sw));
        LOG.warning(sw.toString());
        throw new Fault(new RuntimeException(ex.getMessage() + ", stacktrace: " + sw.toString()));
    }

}
 
Example 3
Source File: SamlFormOutInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    Form form = getRequestForm(message);
    if (form == null) {
        return;
    }

    try {
        SamlAssertionWrapper assertionWrapper = SAMLUtils.createAssertion(message);

        Document doc = DOMUtils.newDocument();
        Element assertionElement = assertionWrapper.toDOM(doc);
        String encodedToken = encodeToken(DOM2Writer.nodeToString(assertionElement));

        updateForm(form, encodedToken);
    } catch (Exception ex) {
        StringWriter sw = new StringWriter();
        ex.printStackTrace(new PrintWriter(sw));
        LOG.warning(sw.toString());
        throw new Fault(new RuntimeException(ex.getMessage() + ", stacktrace: " + sw.toString()));
    }

}
 
Example 4
Source File: AbstractSamlResponseCreator.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
protected Element createLogoutResponse(Idp idp, String statusValue,
                                       String destination, String requestID) throws Exception {
    Document doc = DOMUtils.newDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(statusValue, null);
    String issuer = useRealmForIssuer ? idp.getRealm() : idp.getIdpUrl().toString();
    LogoutResponse response =
        SAML2PResponseComponentBuilder.createSAMLLogoutResponse(requestID, issuer, status, destination);

    // Sign the LogoutResponse
    signResponse(response, idp);

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);

    return policyElement;
}
 
Example 5
Source File: LogicalHandlerFaultOutInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    if (binding.getHandlerChain().isEmpty()) {
        return;
    }
    HandlerChainInvoker invoker = getInvoker(message);
    if (invoker.getLogicalHandlers().isEmpty()) {
        return;
    }

    XMLStreamWriter origWriter = message.getContent(XMLStreamWriter.class);
    Document doc = DOMUtils.newDocument();
    message.setContent(Node.class, doc);
    W3CDOMStreamWriter writer = new W3CDOMStreamWriter(doc);
    // set up the namespace context
    try {
        writer.setNamespaceContext(origWriter.getNamespaceContext());
    } catch (XMLStreamException ex) {
        // don't set the namespaceContext
    }
    // Replace stax writer with DomStreamWriter
    message.setContent(XMLStreamWriter.class, writer);
    message.put(ORIGINAL_WRITER, origWriter);

    message.getInterceptorChain().add(ending);
}
 
Example 6
Source File: LogicalHandlerOutInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    if (binding.getHandlerChain().isEmpty()) {
        return;
    }
    HandlerChainInvoker invoker = getInvoker(message);
    if (invoker.getLogicalHandlers().isEmpty()) {
        return;
    }

    XMLStreamWriter origWriter = message.getContent(XMLStreamWriter.class);

    Node nd = message.getContent(Node.class);
    SOAPMessage m = message.getContent(SOAPMessage.class);
    Document document = null;

    if (m != null) {
        document = m.getSOAPPart();
    } else if (nd != null) {
        document = nd.getOwnerDocument();
    } else {
        document = DOMUtils.newDocument();
        message.setContent(Node.class, document);
    }

    W3CDOMStreamWriter writer = new W3CDOMStreamWriter(document.createDocumentFragment());

    // Replace stax writer with DomStreamWriter
    message.setContent(XMLStreamWriter.class, writer);
    message.put(ORIGINAL_WRITER, origWriter);

    message.getInterceptorChain().add(ending);
}
 
Example 7
Source File: StaxUtilsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultMaxAttributeCount() throws XMLStreamException {
    Document doc = DOMUtils.newDocument();
    Element documentElement = doc.createElementNS(null, "root");
    doc.appendChild(documentElement);

    for (int i = 0; i < 300; i++) {
        documentElement.setAttributeNS(null, "attr-" + i, Integer.toString(i));
    }

    // Should be OK
    XMLStreamReader reader = StaxUtils.createXMLStreamReader(new StringReader(StaxUtils.toString(doc)));
    assertNotNull(StaxUtils.read(reader));

    for (int i = 300; i < 800; i++) {
        documentElement.setAttributeNS(null, "attr-" + i, Integer.toString(i));
    }

    assertTrue(documentElement.getAttributes().getLength() > 500);

    // Should fail as we are over the max attribute count
    reader = StaxUtils.createXMLStreamReader(new StringReader(StaxUtils.toString(doc)));
    try {
        StaxUtils.read(reader);
        fail("Failure expected on exceeding the limit");
    } catch (XMLStreamException ex) {
        assertTrue(ex.getMessage().contains("Attribute limit"));
    }
}
 
Example 8
Source File: StaxUtilsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsSecureReader() {
    Document doc = DOMUtils.newDocument();
    Element documentElement = doc.createElementNS(null, "root");
    doc.appendChild(documentElement);

    XMLStreamReader reader = StaxUtils.createXMLStreamReader(new StringReader(StaxUtils.toString(doc)));
    assertTrue(StaxUtils.isSecureReader(reader, null));
}
 
Example 9
Source File: GreeterImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
public DOMSource sayHi(DOMSource in) {
    Document doc = DOMUtils.newDocument();
    Element el = doc.createElementNS("http://apache.org/hello_world_soap_http_source/source/types",
        "ns1:sayHiResponse");
    Element el2 = doc.createElementNS("http://apache.org/hello_world_soap_http_source/source/types",
        "ns1:responseType");
    el2.appendChild(doc.createTextNode("Bonjour"));
    el.appendChild(el2);
    doc.appendChild(el);
    return new DOMSource(doc);
}
 
Example 10
Source File: JAXRSOAuth2Test.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testSAML2BearerAuthenticationDirect() throws Exception {
    String address = "https://localhost:" + port + "/oauth2-auth/token";
    WebClient wc = createWebClient(address);

    Crypto crypto = new CryptoLoader().loadCrypto(CRYPTO_RESOURCE_PROPERTIES);
    SelfSignInfo signInfo = new SelfSignInfo(crypto, "alice", "password");

    SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(true);
    samlCallbackHandler.setIssuer("alice");
    String audienceURI = "https://localhost:" + port + "/oauth2-auth/token";
    samlCallbackHandler.setAudience(audienceURI);
    SamlAssertionWrapper assertionWrapper = SAMLUtils.createAssertion(samlCallbackHandler,
                                                                      signInfo);
    Document doc = DOMUtils.newDocument();
    Element assertionElement = assertionWrapper.toDOM(doc);
    String assertion = DOM2Writer.nodeToString(assertionElement);

    String encodedAssertion = Base64UrlUtility.encode(assertion);

    Map<String, String> extraParams = new HashMap<>();
    extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE, Constants.CLIENT_AUTH_SAML2_BEARER);
    extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, encodedAssertion);

    ClientAccessToken at = OAuthClientUtils.getAccessToken(wc,
                                                           new CustomGrant(),
                                                           extraParams);
    assertNotNull(at.getTokenKey());
}
 
Example 11
Source File: SamlResponseErrorCreator.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
public String createSAMLResponse(RequestContext context, boolean logout, boolean requestor,
                                 Idp idp, String requestID, String destination) throws ProcessingException {
    Document doc = DOMUtils.newDocument();

    String statusValue = "urn:oasis:names:tc:SAML:2.0:status:Responder";
    if (requestor) {
        statusValue = "urn:oasis:names:tc:SAML:2.0:status:Requester";
    }

    Status status =
        SAML2PResponseComponentBuilder.createStatus(statusValue, null);
    Element responseElement = null;
    try {
        if (logout) {
            responseElement = createLogoutResponse(idp, statusValue, destination, requestID);
        } else {
            Response response =
                SAML2PResponseComponentBuilder.createSAMLResponse(requestID, idp.getRealm(), status);
            Element policyElement = OpenSAMLUtil.toDom(response, doc);
            doc.appendChild(policyElement);

            responseElement = policyElement;
        }

        return encodeResponse(responseElement);
    } catch (Exception e) {
        LOG.warn("Error marshalling SAML Token: {}", e.getMessage());
        throw new ProcessingException(TYPE.BAD_REQUEST);
    }
}
 
Example 12
Source File: BinarySecurityTokenTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testBinarySecurityToken() throws Exception {

    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = BinarySecurityTokenTest.class.getResource("client.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);

    URL wsdl = BinarySecurityTokenTest.class.getResource("DoubleItTokens.wsdl");
    Service service = Service.create(wsdl, SERVICE_QNAME);

    // Successful invocation
    QName portQName = new QName(NAMESPACE, "DoubleItBinarySecurityTokenPort");
    DoubleItPortType port = service.getPort(portQName, DoubleItPortType.class);
    updateAddressPort(port, PORT);

    // Mock up a BinarySecurityToken to add
    SecurityToken securityToken = new SecurityToken();
    securityToken.setId("_" + UUID.randomUUID().toString());

    Document doc = DOMUtils.newDocument();
    BinarySecurity binarySecurity = new BinarySecurity(doc);
    binarySecurity.setValueType("http://custom-value-type");
    binarySecurity.setToken("This is a token".getBytes());

    securityToken.setToken(binarySecurity.getElement());

    ((BindingProvider)port).getRequestContext().put(SecurityConstants.TOKEN, securityToken);

    assertEquals(50, port.doubleIt(25));

    ((java.io.Closeable)port).close();
    bus.shutdown(true);
}
 
Example 13
Source File: SAML2ITCase.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Test
public void validateIdpInitiatedLoginResponseFailure() throws Exception {
    assumeTrue(SAML2SPDetector.isSAML2SPAvailable());

    SAML2SPService saml2Service = anonymous.getService(SAML2SPService.class);

    // Create a SAML Response using WSS4J
    SAML2ReceivedResponseTO response = new SAML2ReceivedResponseTO();
    response.setSpEntityID("http://recipient.apache.org/");
    response.setUrlContext("saml2sp");

    org.opensaml.saml.saml2.core.Response samlResponse =
            createResponse(null, true, SAML2Constants.CONF_BEARER, "urn:org:apache:cxf:fediz:idp:realm-A");

    Document doc = DOMUtils.newDocument();
    Element responseElement = OpenSAMLUtil.toDom(samlResponse, doc);
    String responseStr = DOM2Writer.nodeToString(responseElement);

    // Validate the SAML Response
    response.setSamlResponse(Base64.getEncoder().encodeToString(responseStr.getBytes()));
    response.setRelayState("idpInitiated");
    try {
        saml2Service.validateLoginResponse(response);
        fail("Failure expected on an unsolicited login");
    } catch (SyncopeClientException e) {
        assertNotNull(e);
    }
}
 
Example 14
Source File: StaxUtilsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultMaxAttributeLength() throws XMLStreamException {
    Document doc = DOMUtils.newDocument();
    Element documentElement = doc.createElementNS(null, "root");
    doc.appendChild(documentElement);

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 1024; i++) {
        sb.append(i);
    }

    documentElement.setAttributeNS(null, "attr", sb.toString());

    // Should be OK
    XMLStreamReader reader = StaxUtils.createXMLStreamReader(new StringReader(StaxUtils.toString(doc)));
    assertNotNull(StaxUtils.read(reader));

    for (int i = 0; i < 1024 * 64; i++) {
        sb.append(i);
    }

    documentElement.setAttributeNS(null, "attr", sb.toString());
    assertTrue(documentElement.getAttributeNS(null, "attr").length() > (1024 * 64));

    // Should fail as we are over the max attribute length
    reader = StaxUtils.createXMLStreamReader(new StringReader(StaxUtils.toString(doc)));
    try {
        StaxUtils.read(reader);
        fail("Failure expected on exceeding the limit");
    } catch (XMLStreamException ex) {
        assertTrue(ex.getMessage().contains("Maximum attribute size limit"));
    }

}
 
Example 15
Source File: SAMLClaimsTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSAML2Claims() throws Exception {
    AttributeBean attributeBean = new AttributeBean();
    attributeBean.setQualifiedName(SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT);
    attributeBean.setNameFormat(SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED);
    attributeBean.addAttributeValue("employee");

    SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler();
    samlCallbackHandler.setAttributes(Collections.singletonList(attributeBean));

    // Create the SAML Assertion via the CallbackHandler
    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(samlCallbackHandler, samlCallback);
    SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback);

    Document doc = DOMUtils.newDocument();
    samlAssertion.toDOM(doc);

    ClaimCollection claims = SAMLUtils.getClaims(samlAssertion);
    assertEquals(claims.getDialect().toString(),
            "http://schemas.xmlsoap.org/ws/2005/05/identity");
    assertEquals(1, claims.size());

    // Check Claim values
    Claim claim = claims.get(0);
    assertEquals(claim.getClaimType(), SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT);
    assertEquals(1, claim.getValues().size());
    assertTrue(claim.getValues().contains("employee"));

    // Check SAMLClaim values
    assertTrue(claim instanceof SAMLClaim);
    assertEquals(SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT, ((SAMLClaim)claim).getName());
    assertEquals(SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED, ((SAMLClaim)claim).getNameFormat());

    // Check roles
    Set<Principal> roles =
            SAMLUtils.parseRolesFromClaims(claims,
                    SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT,
                    SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED);
    assertEquals(1, roles.size());
    Principal p = roles.iterator().next();
    assertEquals("employee", p.getName());
}
 
Example 16
Source File: SAMLClaimsTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSAML2MultipleRoles() throws Exception {
    AttributeBean attributeBean = new AttributeBean();
    attributeBean.setQualifiedName(SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT);
    attributeBean.setNameFormat(SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED);
    attributeBean.addAttributeValue("employee");
    attributeBean.addAttributeValue("boss");

    SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler();
    samlCallbackHandler.setAttributes(Collections.singletonList(attributeBean));

    // Create the SAML Assertion via the CallbackHandler
    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(samlCallbackHandler, samlCallback);
    SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback);

    Document doc = DOMUtils.newDocument();
    samlAssertion.toDOM(doc);

    ClaimCollection claims = SAMLUtils.getClaims(samlAssertion);
    assertEquals(claims.getDialect().toString(),
            "http://schemas.xmlsoap.org/ws/2005/05/identity");
    assertEquals(1, claims.size());

    // Check Claim values
    Claim claim = claims.get(0);
    assertEquals(claim.getClaimType(), SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT);
    assertEquals(2, claim.getValues().size());
    assertTrue(claim.getValues().contains("employee"));
    assertTrue(claim.getValues().contains("boss"));

    // Check SAMLClaim values
    assertTrue(claim instanceof SAMLClaim);
    assertEquals(SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT, ((SAMLClaim)claim).getName());
    assertEquals(SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED, ((SAMLClaim)claim).getNameFormat());

    // Check roles
    Set<Principal> roles =
            SAMLUtils.parseRolesFromClaims(claims,
                    SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT,
                    SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED);
    assertEquals(2, roles.size());
}
 
Example 17
Source File: SAMLClaimsTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSAML2MultipleClaims() throws Exception {
    AttributeBean attributeBean = new AttributeBean();
    attributeBean.setQualifiedName(SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT);
    attributeBean.setNameFormat(SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED);
    attributeBean.addAttributeValue("employee");

    AttributeBean attributeBean2 = new AttributeBean();
    attributeBean2.setQualifiedName(
            "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname");
    attributeBean2.setNameFormat(SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED);
    attributeBean2.addAttributeValue("smith");

    SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler();
    List<AttributeBean> attributes = new ArrayList<>();
    attributes.add(attributeBean);
    attributes.add(attributeBean2);
    samlCallbackHandler.setAttributes(attributes);

    // Create the SAML Assertion via the CallbackHandler
    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(samlCallbackHandler, samlCallback);
    SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback);

    Document doc = DOMUtils.newDocument();
    samlAssertion.toDOM(doc);

    ClaimCollection claims = SAMLUtils.getClaims(samlAssertion);
    assertEquals(claims.getDialect().toString(),
            "http://schemas.xmlsoap.org/ws/2005/05/identity");
    assertEquals(2, claims.size());

    // Check roles
    Set<Principal> roles =
            SAMLUtils.parseRolesFromClaims(claims,
                    SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT,
                    SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED);
    assertEquals(1, roles.size());
    Principal p = roles.iterator().next();
    assertEquals("employee", p.getName());
}
 
Example 18
Source File: X509TokenTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testAsymmetricIssuerSerialDispatchMessage() throws Exception {

    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = X509TokenTest.class.getResource("client.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);

    URL wsdl = X509TokenTest.class.getResource("DoubleItX509.wsdl");
    Service service = Service.create(wsdl, SERVICE_QNAME);
    QName portQName = new QName(NAMESPACE, "DoubleItAsymmetricIssuerSerialOperationPort");

    Dispatch<SOAPMessage> disp = service.createDispatch(portQName, SOAPMessage.class, Mode.MESSAGE);
    updateAddressPort(disp, test.getPort());

    if (test.isStreaming()) {
        SecurityTestUtil.enableStreaming(disp);
    }

    Document xmlDocument = DOMUtils.newDocument();

    Element requestElement = xmlDocument.createElementNS("http://www.example.org/schema/DoubleIt", "tns:DoubleIt");
    requestElement.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:tns",
                                  "http://www.example.org/schema/DoubleIt");
    Element dataElement = xmlDocument.createElement("numberToDouble");
    dataElement.appendChild(xmlDocument.createTextNode("25"));
    requestElement.appendChild(dataElement);
    xmlDocument.appendChild(requestElement);

    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage request = factory.createMessage();
    request.getSOAPBody().appendChild(request.getSOAPPart().adoptNode(requestElement));

    // We need to set the wsdl operation name here, or otherwise the policy layer won't pick
    // up the security policy attached at the operation level
    // this can be done in one of three ways:
    // 1) set the WSDL_OPERATION context property
    //    QName wsdlOperationQName = new QName(NAMESPACE, "DoubleIt");
    //    disp.getRequestContext().put(MessageContext.WSDL_OPERATION, wsdlOperationQName);
    // 2) Set the "find.dispatch.operation" to TRUE to have  CXF explicitly try and determine it from the payload
    disp.getRequestContext().put("find.dispatch.operation", Boolean.TRUE);
    // 3) Turn on WS-Addressing as that will force #2
    //    TODO - add code for this, really is adding WS-Addressing feature to the createDispatch call above

    SOAPMessage resp = disp.invoke(request);
    Node nd = resp.getSOAPBody().getFirstChild();

    Map<String, String> ns = new HashMap<>();
    ns.put("ns2", "http://www.example.org/schema/DoubleIt");
    XPathUtils xp = new XPathUtils(ns);
    Object o = xp.getValue("//ns2:DoubleItResponse/doubledNumber", 
                           DOMUtils.getDomElement(nd), XPathConstants.STRING);
    assertEquals(StaxUtils.toString(nd), "50", o);

    bus.shutdown(true);
}
 
Example 19
Source File: W3CDOMStreamWriter.java    From cxf with Apache License 2.0 4 votes vote down vote up
public W3CDOMStreamWriter() {
    document = DOMUtils.newDocument();
}
 
Example 20
Source File: SAML2ITCase.java    From syncope with Apache License 2.0 4 votes vote down vote up
@Test
public void loginResponseWrappingAttack() throws Exception {
    assumeTrue(SAML2SPDetector.isSAML2SPAvailable());

    // Get a valid login request for the Fediz realm
    SAML2SPService saml2Service = anonymous.getService(SAML2SPService.class);
    SAML2RequestTO loginRequest = saml2Service.createLoginRequest(ADDRESS, "urn:org:apache:cxf:fediz:idp:realm-A");
    assertNotNull(loginRequest);

    SAML2ReceivedResponseTO response = new SAML2ReceivedResponseTO();
    response.setSpEntityID("http://recipient.apache.org/");
    response.setUrlContext("saml2sp");
    response.setRelayState(loginRequest.getRelayState());

    // Create a SAML Response using WSS4J
    JwsJwtCompactConsumer relayState = new JwsJwtCompactConsumer(response.getRelayState());
    String inResponseTo = relayState.getJwtClaims().getSubject();

    org.opensaml.saml.saml2.core.Response samlResponse = createResponse(inResponseTo);

    Document doc = DOMUtils.newDocument();
    Element responseElement = OpenSAMLUtil.toDom(samlResponse, doc);
    assertNotNull(responseElement);
    doc.appendChild(responseElement);

    // Get Assertion Element
    Element assertionElement =
            (Element) responseElement.getElementsByTagNameNS(SAMLConstants.SAML20_NS, "Assertion").item(0);
    assertNotNull(assertionElement);

    // Clone it, strip the Signature, modify the Subject, change Subj Conf
    Element clonedAssertion = (Element) assertionElement.cloneNode(true);
    clonedAssertion.setAttributeNS(null, "ID", "_12345623562");
    Element sigElement =
            (Element) clonedAssertion.getElementsByTagNameNS(WSConstants.SIG_NS, "Signature").item(0);
    clonedAssertion.removeChild(sigElement);

    Element subjElement =
            (Element) clonedAssertion.getElementsByTagNameNS(SAMLConstants.SAML20_NS, "Subject").item(0);
    Element subjNameIdElement =
            (Element) subjElement.getElementsByTagNameNS(SAMLConstants.SAML20_NS, "NameID").item(0);
    subjNameIdElement.setTextContent("verdi");

    Element subjConfElement =
            (Element) subjElement.getElementsByTagNameNS(SAMLConstants.SAML20_NS, "SubjectConfirmation").item(0);
    subjConfElement.setAttributeNS(null, "Method", SAML2Constants.CONF_SENDER_VOUCHES);

    // Now insert the modified cloned Assertion into the Response after the other assertion
    responseElement.insertBefore(clonedAssertion, null);

    String responseStr = DOM2Writer.nodeToString(responseElement);

    // Validate the SAML Response
    response.setSamlResponse(Base64.getEncoder().encodeToString(responseStr.getBytes()));
    try {
        saml2Service.validateLoginResponse(response);
        fail("Failure expected on an unsigned Assertion");
    } catch (SyncopeClientException e) {
        assertNotNull(e);
    }
}