com.gargoylesoftware.htmlunit.html.DomNodeList Java Examples

The following examples show how to use com.gargoylesoftware.htmlunit.html.DomNodeList. 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: SgmlPage.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public DomNodeList<DomElement> getElementsByTagName(final String tagName) {
    return new AbstractDomNodeList<DomElement>(this) {
        @Override
        protected List<DomElement> provideElements() {
            final List<DomElement> res = new LinkedList<>();
            final boolean caseSensitive = hasCaseSensitiveTagNames();
            for (final DomElement elem : getDomElementDescendants()) {
                final String localName = elem.getLocalName();
                if ("*".equals(tagName) || localName.equals(tagName)
                        || (!caseSensitive && localName.equalsIgnoreCase(tagName))) {
                    res.add(elem);
                }
            }
            return res;
        }
    };
}
 
Example #2
Source File: HTTPTestUtils.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
public static void logoutCleanup(String url, CookieManager cookieManager) throws IOException {
    final WebClient webClient = new WebClient();
    webClient.setCookieManager(cookieManager);
    webClient.getOptions().setUseInsecureSSL(true);
    final HtmlPage idpPage = webClient.getPage(url);

    Assert.assertEquals("IDP SignOut Response Page", idpPage.getTitleText());

    Assert.assertTrue(idpPage.asText().contains("CXF Fediz IDP successful logout"));

    DomNodeList<DomElement> images = idpPage.getElementsByTagName("img");
    Assert.assertEquals(1, images.getLength());
    for (int i = 0; i < images.size(); i++) {
        DomElement domElement = images.get(i);
        String imgSrc = domElement.getAttribute("src");

        //we should get a fault if the image isn't available.
        webClient.getPage(imgSrc);
    }

    webClient.close();
}
 
Example #3
Source File: SimpleRange.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
private static void deleteBefore(final DomNode node, int offset) {
    if (isOffsetChars(node)) {
        String text = getText(node);
        if (offset > -1 && offset < text.length()) {
            text = text.substring(offset);
        }
        else {
            text = "";
        }
        setText(node, text);
    }
    else {
        final DomNodeList<DomNode> children = node.getChildNodes();
        for (int i = 0; i < offset && i < children.getLength(); i++) {
            final DomNode child = children.get(i);
            child.remove();
            i--;
            offset--;
        }
    }
}
 
Example #4
Source File: SimpleRange.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
private static void deleteAfter(final DomNode node, final int offset) {
    if (isOffsetChars(node)) {
        String text = getText(node);
        if (offset > -1 && offset < text.length()) {
            text = text.substring(0, offset);
            setText(node, text);
        }
    }
    else {
        final DomNodeList<DomNode> children = node.getChildNodes();
        for (int i = offset; i < children.getLength(); i++) {
            final DomNode child = children.get(i);
            child.remove();
            i--;
        }
    }
}
 
Example #5
Source File: SgmlPageTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void getElementsByTagNameAsterisk() throws Exception {
    final String html
        = "<html><head><title>First</title></head>\n"
        + "<body>\n"
        + "<form><input type='button' name='button1' value='pushme'></form>\n"
        + "<div>a</div> <div>b</div> <div>c</div>\n"
        + "</body></html>";

    final HtmlPage page = loadPage(html);

    final DomNodeList<DomElement> elements = page.getElementsByTagName("*");

    assertEquals(9, elements.getLength());
    validateDomNodeList(elements);

    final HtmlDivision newDiv = new HtmlDivision(HtmlDivision.TAG_NAME, page, null);
    page.getBody().appendChild(newDiv);
    assertEquals(10, elements.getLength());
    validateDomNodeList(elements);
}
 
Example #6
Source File: SgmlPageTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void getElementsByTagNameNSAsterisk() throws Exception {
    final String html
        = "<html><head><title>First</title></head>\n"
        + "<body>\n"
        + "<form><input type='button' name='button1' value='pushme'></form>\n"
        + "<div>a</div> <div>b</div> <div>c</div>\n"
        + "</body></html>";

    final HtmlPage page = loadPage(html);

    final DomNodeList<DomElement> elements = page.getElementsByTagNameNS(Html.XHTML_NAMESPACE, "*");

    assertEquals(9, elements.getLength());
    validateDomNodeList(elements);

    final HtmlDivision newDiv = new HtmlDivision(HtmlDivision.TAG_NAME, page, null);
    page.getBody().appendChild(newDiv);
    assertEquals(10, elements.getLength());
    validateDomNodeList(elements);
}
 
Example #7
Source File: WebClient8Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if something goes wrong
 */
@Test
public void appendChildMoved() throws Exception {
    final String html = "<html>\n"
            + "<head><title>foo</title></head>\n"
            + "<body>\n"
            + "<p>hello</p>\n"
            + "</body></html>";

    final String html2 = "<html>\n"
            + "<head><title>foo</title></head>\n"
            + "<body>\n"
            + "<p id='tester'>world</p>\n"
            + "</body></html>";

    try (WebClient webClient = new WebClient(getBrowserVersion(), false, null, -1)) {
        final HtmlPage page = loadPage(webClient, html, null, URL_FIRST);
        final HtmlPage page2 = loadPage(webClient, html2, null, URL_SECOND);

        final DomNodeList<DomElement> elements = page.getElementsByTagName("*");
        assertEquals(5, elements.getLength());

        page.getBody().appendChild(page2.getElementById("tester"));
        assertEquals(6, elements.getLength());
    }
}
 
Example #8
Source File: SgmlPage.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public DomNodeList<DomElement> getElementsByTagName(final String tagName) {
    return new AbstractDomNodeList<DomElement>(this) {
        @Override
        protected List<DomElement> provideElements() {
            final List<DomElement> res = new LinkedList<>();
            final boolean caseSensitive = hasCaseSensitiveTagNames();
            for (final DomElement elem : getDomElementDescendants()) {
                final String localName = elem.getLocalName();
                if ("*".equals(tagName) || localName.equals(tagName)
                        || (!caseSensitive && localName.equalsIgnoreCase(tagName))) {
                    res.add(elem);
                }
            }
            return res;
        }
    };
}
 
Example #9
Source File: SimpleRange.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
private static void deleteBefore(final DomNode node, int offset) {
    if (isOffsetChars(node)) {
        String text = getText(node);
        if (offset > -1 && offset < text.length()) {
            text = text.substring(offset);
        }
        else {
            text = "";
        }
        setText(node, text);
    }
    else {
        final DomNodeList<DomNode> children = node.getChildNodes();
        for (int i = 0; i < offset && i < children.getLength(); i++) {
            final DomNode child = children.get(i);
            child.remove();
            i--;
            offset--;
        }
    }
}
 
Example #10
Source File: SimpleRange.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
private static void deleteAfter(final DomNode node, final int offset) {
    if (isOffsetChars(node)) {
        String text = getText(node);
        if (offset > -1 && offset < text.length()) {
            text = text.substring(0, offset);
            setText(node, text);
        }
    }
    else {
        final DomNodeList<DomNode> children = node.getChildNodes();
        for (int i = offset; i < children.getLength(); i++) {
            final DomNode child = children.get(i);
            child.remove();
            i--;
        }
    }
}
 
Example #11
Source File: HTTPTestUtils.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
public static void logout(String url, CookieManager cookieManager, boolean wsfed) throws IOException {
    final WebClient webClient = new WebClient();
    webClient.setCookieManager(cookieManager);
    webClient.getOptions().setUseInsecureSSL(true);
    final HtmlPage idpPage = webClient.getPage(url);

    Assert.assertEquals("IDP SignOut Confirmation Response Page", idpPage.getTitleText());

    final HtmlForm form = idpPage.getFormByName("signoutconfirmationresponseform");
    final HtmlSubmitInput button = form.getInputByName("_eventId_submit");

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpLogoutPage = button.click();
    webClient.getOptions().setJavaScriptEnabled(true);

    if (wsfed) {
        DomNodeList<DomElement> images = idpLogoutPage.getElementsByTagName("img");
        Assert.assertEquals(1, images.getLength());
        for (int i = 0; i < images.size(); i++) {
            DomElement domElement = images.get(i);
            String imgSrc = domElement.getAttribute("src");

            //we should get a fault if the image isn't available.
            webClient.getPage(imgSrc);
        }
    } else {
        // For SAML SSO we will be redirected back to the RP
        HtmlForm responseForm = idpLogoutPage.getFormByName("samlsignoutresponseform");
        HtmlSubmitInput button2 = responseForm.getInputByName("_eventId_submit");
        button2.click();
    }

    webClient.close();
}
 
Example #12
Source File: WReqTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private static String login(String url, String user, String password, String idpPort) throws IOException {
    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(idpPort)),
        new UsernamePasswordCredentials(user, password));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);
    webClient.getOptions().setJavaScriptEnabled(true);
    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    // Test the SAML Version here
    DomNodeList<DomElement> results = idpPage.getElementsByTagName("input");

    String wresult = null;
    for (DomElement result : results) {
        if ("wresult".equals(result.getAttributeNS(null, "name"))) {
            wresult = result.getAttributeNS(null, "value");
            break;
        }
    }
    Assert.assertTrue(wresult != null
        && wresult.contains("urn:oasis:names:tc:SAML:1.0:cm:bearer"));

    final HtmlForm form = idpPage.getFormByName("signinresponseform");
    final HtmlSubmitInput button = form.getInputByName("_eventId_submit");

    final HtmlPage rpPage = button.click();
    Assert.assertEquals("WS Federation Systests Examples", rpPage.getTitleText());

    webClient.close();
    return rpPage.getBody().getTextContent();
}
 
Example #13
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testSuccessfulInvokeOnIdP() throws Exception {
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
    url += "wa=wsignin1.0";
    url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
    url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
    String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
    url += "&wreply=" + wreply;

    String user = "alice";
    String password = "ecila";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(user, password));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);
    webClient.getOptions().setJavaScriptEnabled(true);
    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    // Parse the form to get the token (wresult)
    DomNodeList<DomElement> results = idpPage.getElementsByTagName("input");

    String wresult = null;
    for (DomElement result : results) {
        if ("wresult".equals(result.getAttributeNS(null, "name"))) {
            wresult = result.getAttributeNS(null, "value");
            break;
        }
    }

    Assert.assertNotNull(wresult);

    webClient.close();
}
 
Example #14
Source File: PackageDetectorsITest.java    From warnings-ng-plugin with MIT License 5 votes vote down vote up
private List<String> getLinksWithGivenTargetName(final HtmlPage page, final String targetName) {
    List<DomElement> htmlElement = page.getElementsByIdAndOrName(targetName);
    ArrayList<String> links = new ArrayList<>();
    for (DomElement element : htmlElement) {
        DomNodeList<HtmlElement> domNodeList = element.getElementsByTagName("a");
        for (HtmlElement htmlElementHref : domNodeList) {
            links.add(htmlElementHref.getAttribute("href"));
        }
    }
    return links;
}
 
Example #15
Source File: ExtractingLinksWithHtmlUnit.java    From chuidiang-ejemplos with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
   WebClient webClient = new WebClient();
   HtmlPage page = webClient.getPage("http://www.gnu.org/home.es.html");
   
   DomNodeList<DomElement> nodeList = page.getElementsByTagName("a");
   for (DomElement element : nodeList){
      System.out.println(element.getTextContent()+ " -> " +element.getAttribute("href"));
   }

}
 
Example #16
Source File: KubernetesCloudTest.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
public HtmlInput getInputByName(DomElement root, String name) {
    DomNodeList<HtmlElement> inputs = root.getElementsByTagName("input");
    for (HtmlElement input : inputs) {
        if (name.equals(input.getAttribute("name"))) {
            return (HtmlInput) input;
        }
    }
    return null;
}
 
Example #17
Source File: DemoApplicationTests.java    From keycloak-springsecurity5-sample with GNU General Public License v3.0 5 votes vote down vote up
private void assertIndexPage(HtmlPage page) throws Exception {
	assertThat(page.getTitleText()).isEqualTo("Spring Security - OAuth 2.0 Login");

	DomNodeList<HtmlElement> divElements = page.getBody().getElementsByTagName("div");
	assertThat(divElements.get(1).asText()).contains("User: [email protected]");
	assertThat(divElements.get(4).asText()).contains("You are successfully logged in [email protected]");
}
 
Example #18
Source File: ExternalTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that we use the latest gecko driver.
 * @throws Exception if an error occurs
 */
@Test
public void assertGeckoDriver() throws Exception {
    try (WebClient webClient = buildWebClient()) {
        try {
            final HtmlPage page = webClient.getPage("https://github.com/mozilla/geckodriver/releases/latest");
            final DomNodeList<DomNode> divs = page.querySelectorAll(".release-header div");
            assertEquals("Gecko Driver", divs.get(0).asText(), "v" + GECKO_DRIVER_);
        }
        catch (final FailingHttpStatusCodeException e) {
            // ignore
        }
    }
}
 
Example #19
Source File: SgmlPageTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private <E extends DomNode> void validateDomNodeList(final DomNodeList<E> nodes) {
    assertEquals(nodes.getLength(), nodes.size());
    final Iterator<E> nodesIterator = nodes.iterator();
    for (int i = 0; i < nodes.getLength(); i++) {
        assertEquals(nodes.item(i), nodes.get(i));
        assertEquals(nodes.item(i), nodesIterator.next());
        assertEquals(i, nodes.indexOf(nodes.item(i)));
    }
    assertEquals(false, nodesIterator.hasNext());
    final ListIterator<E> nodesListIterator = nodes.listIterator();
    assertEquals(nodes.item(0), nodesListIterator.next());
    assertEquals(nodes.item(1), nodesListIterator.next());
    assertEquals(nodes.item(1), nodesListIterator.previous());
}
 
Example #20
Source File: SgmlPage.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public DomNodeList<DomElement> getElementsByTagNameNS(final String namespaceURI, final String localName) {
    return new AbstractDomNodeList<DomElement>(this) {
        @Override
        protected List<DomElement> provideElements() {
            final List<DomElement> res = new LinkedList<>();
            final Comparator<String> comparator;

            if (hasCaseSensitiveTagNames()) {
                comparator = Comparator.nullsFirst(String::compareTo);
            }
            else {
                comparator = Comparator.nullsFirst(String::compareToIgnoreCase);
            }

            for (final DomElement elem : getDomElementDescendants()) {
                final String locName = elem.getLocalName();

                if (("*".equals(namespaceURI) || comparator.compare(namespaceURI, elem.getNamespaceURI()) == 0)
                        && ("*".equals(locName) || comparator.compare(locName, elem.getLocalName()) == 0)) {
                    res.add(elem);
                }
            }
            return res;
        }
    };
}
 
Example #21
Source File: CXFTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testNoRequestValidation() throws Exception {

    String url = "https://localhost:" + getRpHttpsPort() + "/fedizhelloworldcxfnoreqvalidation/secure/fedservlet";

    String user = "alice";
    String password = "ecila";

    // Get the initial token
    CookieManager cookieManager = new CookieManager();
    final WebClient webClient = new WebClient();
    webClient.setCookieManager(cookieManager);
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(user, password));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);
    webClient.getOptions().setJavaScriptEnabled(true);
    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    // Parse the form to remove the context
    DomNodeList<DomElement> results = idpPage.getElementsByTagName("input");

    for (DomElement result : results) {
        if (getContextName().equals(result.getAttributeNS(null, "name"))) {
            result.setAttributeNS(null, "value", "");
        }
    }

    // Invoke back on the RP

    final HtmlForm form = idpPage.getFormByName(getLoginFormName());
    final HtmlSubmitInput button = form.getInputByName("_eventId_submit");

    final HtmlPage rpPage = button.click();
    Assert.assertTrue("WS Federation Systests Examples".equals(rpPage.getTitleText())
                      || "WS Federation Systests Spring Examples".equals(rpPage.getTitleText()));

    webClient.close();

}
 
Example #22
Source File: TomcatPluginTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@Test
public void testAliceModifiedContext() throws Exception {

    String url = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName()
        + "/secure/fedservlet";
    String user = "alice";
    String password = "ecila";

    // Get the initial token
    CookieManager cookieManager = new CookieManager();
    final WebClient webClient = new WebClient();
    webClient.setCookieManager(cookieManager);
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(user, password));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);
    webClient.getOptions().setJavaScriptEnabled(true);
    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    // Parse the form to get the token (wresult)
    DomNodeList<DomElement> results = idpPage.getElementsByTagName("input");

    for (DomElement result : results) {
        if (getContextName().equals(result.getAttributeNS(null, "name"))) {
            // Now modify the context
            String value = result.getAttributeNS(null, "value");
            value = "H" + value;
            result.setAttributeNS(null, "value", value);
        }
    }

    // Invoke back on the RP

    final HtmlForm form = idpPage.getFormByName(getLoginFormName());
    final HtmlSubmitInput button = form.getInputByName("_eventId_submit");

    try {
        button.click();
        Assert.fail("Failure expected on a modified context");
    } catch (FailingHttpStatusCodeException ex) {
        // Request Timeout expected here, as the context isn't known - the session is presumed to have expired
        Assert.assertTrue(408 == ex.getStatusCode());
    }

    webClient.close();
}
 
Example #23
Source File: TomcatPluginTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@Test
public void testModifiedSignatureValue() throws Exception {

    String url = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName()
        + "/secure/fedservlet";
    String user = "alice";
    String password = "ecila";

    // Get the initial token
    CookieManager cookieManager = new CookieManager();
    final WebClient webClient = new WebClient();
    webClient.setCookieManager(cookieManager);
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(user, password));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);
    webClient.getOptions().setJavaScriptEnabled(true);
    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    // Parse the form to get the token (wresult)
    DomNodeList<DomElement> results = idpPage.getElementsByTagName("input");

    for (DomElement result : results) {
        if (getTokenName().equals(result.getAttributeNS(null, "name"))) {
            String value = result.getAttributeNS(null, "value");

            // Decode response
            byte[] deflatedToken = Base64Utility.decode(value);
            InputStream inputStream = new ByteArrayInputStream(deflatedToken);

            Document responseDoc = StaxUtils.read(new InputStreamReader(inputStream, "UTF-8"));

            // Modify SignatureValue
            String signatureNamespace = "http://www.w3.org/2000/09/xmldsig#";
            Node signatureValue =
                responseDoc.getElementsByTagNameNS(signatureNamespace, "SignatureValue").item(0);
            signatureValue.setTextContent("H" + signatureValue.getTextContent());

            // Re-encode response
            String responseMessage = DOM2Writer.nodeToString(responseDoc);
            result.setAttributeNS(null, "value", Base64Utility.encode(responseMessage.getBytes()));
        }
    }

    // Invoke back on the RP

    final HtmlForm form = idpPage.getFormByName(getLoginFormName());
    final HtmlSubmitInput button = form.getInputByName("_eventId_submit");

    try {
        button.click();
        Assert.fail("Failure expected on a modified signature");
    } catch (FailingHttpStatusCodeException ex) {
        // expected
        Assert.assertTrue(401 == ex.getStatusCode() || 403 == ex.getStatusCode());
    }

    webClient.close();
}
 
Example #24
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private static org.opensaml.saml.saml2.core.Response parseSAMLResponse(HtmlPage idpPage,
                                                                String relayState,
                                                                String consumerURL,
                                                                String authnRequestId
) throws Exception {
    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    // Parse the form to get the token (SAMLResponse)
    DomNodeList<DomElement> results = idpPage.getElementsByTagName("input");

    String samlResponse = null;
    boolean foundRelayState = false;
    for (DomElement result : results) {
        if ("SAMLResponse".equals(result.getAttributeNS(null, "name"))) {
            samlResponse = result.getAttributeNS(null, "value");
        } else if ("RelayState".equals(result.getAttributeNS(null, "name"))) {
            foundRelayState = true;
            Assert.assertEquals(result.getAttributeNS(null, "value"), relayState);
        }
    }

    Assert.assertNotNull(samlResponse);
    Assert.assertTrue(foundRelayState);

    // Check the "action"
    DomNodeList<DomElement> formResults = idpPage.getElementsByTagName("form");
    Assert.assertFalse(formResults.isEmpty());

    DomElement formResult = formResults.get(0);
    String action = formResult.getAttributeNS(null, "action");
    Assert.assertTrue(action.equals(consumerURL));

    // Decode + verify response
    byte[] deflatedToken = Base64Utility.decode(samlResponse);
    InputStream inputStream = new ByteArrayInputStream(deflatedToken);

    Document responseDoc = StaxUtils.read(new InputStreamReader(inputStream, UTF_8.name()));

    XMLObject responseObject = OpenSAMLUtil.fromDom(responseDoc.getDocumentElement());
    Assert.assertTrue(responseObject instanceof org.opensaml.saml.saml2.core.Response);

    org.opensaml.saml.saml2.core.Response samlResponseObject =
        (org.opensaml.saml.saml2.core.Response)responseObject;
    Assert.assertTrue(authnRequestId.equals(samlResponseObject.getInResponseTo()));

    return samlResponseObject;
}
 
Example #25
Source File: WSFedTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private static String login(String url, String user, String password,
                                       String idpPort, String rpIdpPort) throws IOException {
    //
    // Access the RP + get redirected to the IdP for "realm a". Then get redirected to the IdP for
    // "realm b".
    //
    final WebClient webClient = new WebClient();
    CookieManager cookieManager = new CookieManager();
    webClient.setCookieManager(cookieManager);
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(idpPort)),
        new UsernamePasswordCredentials(user, password));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);
    webClient.getOptions().setJavaScriptEnabled(true);
    assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    // For some reason, redirecting back to the IdP for "realm a" is not working with htmlunit. So extract
    // the parameters manually from the form, and access the IdP for "realm a" with them
    DomNodeList<DomElement> results = idpPage.getElementsByTagName("input");

    String wresult = null;
    String wa = null;
    String wctx = null;
    String wtrealm = null;
    for (DomElement result : results) {
        String name = result.getAttributeNS(null, "name");
        String value = result.getAttributeNS(null, "value");
        if ("wresult".equals(name)) {
            wresult = value;
        } else if ("wa".equals(name)) {
            wa = value;
        } else if ("wctx".equals(name)) {
            wctx = value;
        } else if ("wtrealm".equals(name)) {
            wtrealm = value;
        }
    }
    assertNotNull(wresult);
    assertNotNull(wa);
    assertNotNull(wctx);
    assertNotNull(wtrealm);
    webClient.close();

    // Invoke on the IdP for "realm a"
    final WebClient webClient2 = new WebClient();
    webClient2.setCookieManager(cookieManager);
    webClient2.getOptions().setUseInsecureSSL(true);

    String url2 = "https://localhost:" + rpIdpPort + "/fediz-idp/federation"
            + "?wctx=" + wctx
            + "&wa=" + wa
            + "&wtrealm=" + URLEncoder.encode(wtrealm, "UTF8")
            + "&wresult=" + URLEncoder.encode(wresult, "UTF8");

    webClient2.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage2 = webClient2.getPage(url2);
    webClient2.getOptions().setJavaScriptEnabled(true);
    assertEquals("IDP SignIn Response Form", idpPage2.getTitleText());

    // Now redirect back to the RP
    final HtmlForm form2 = idpPage2.getFormByName("signinresponseform");

    final HtmlSubmitInput button2 = form2.getInputByName("_eventId_submit");

    final HtmlPage rpPage = button2.click();
    assertEquals("WS Federation Systests Examples", rpPage.getTitleText());

    webClient2.close();
    return rpPage.getBody().getTextContent();
}
 
Example #26
Source File: WSFedTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private static String login(String url, String user, String password,
                                       String idpPort, String rpIdpPort) throws IOException {
    //
    // Access the RP + get redirected to the IdP for "realm a". Then get redirected to the IdP for
    // "realm b".
    //
    final WebClient webClient = new WebClient();
    CookieManager cookieManager = new CookieManager();
    webClient.setCookieManager(cookieManager);
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(idpPort)),
        new UsernamePasswordCredentials(user, password));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);
    webClient.getOptions().setJavaScriptEnabled(true);
    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    // For some reason, redirecting back to the IdP for "realm a" is not working with htmlunit. So extract
    // the parameters manually from the form, and access the IdP for "realm a" with them
    DomNodeList<DomElement> results = idpPage.getElementsByTagName("input");

    String wresult = null;
    String wa = "wsignin1.0";
    String wctx = null;
    String wtrealm = null;
    for (DomElement result : results) {
        if ("wresult".equals(result.getAttributeNS(null, "name"))) {
            wresult = result.getAttributeNS(null, "value");
        } else if ("wctx".equals(result.getAttributeNS(null, "name"))) {
            wctx = result.getAttributeNS(null, "value");
        } else if ("wtrealm".equals(result.getAttributeNS(null, "name"))) {
            wtrealm = result.getAttributeNS(null, "value");
        }
    }
    Assert.assertTrue(wctx != null && wresult != null && wtrealm != null);
    webClient.close();

    // Invoke on the IdP for "realm a"
    final WebClient webClient2 = new WebClient();
    webClient2.setCookieManager(cookieManager);
    webClient2.getOptions().setUseInsecureSSL(true);

    String url2 = "https://localhost:" + rpIdpPort + "/fediz-idp/federation?";
    url2 += "wctx=" + wctx + "&";
    url2 += "wa=" + wa + "&";
    url2 += "wtrealm=" + URLEncoder.encode(wtrealm, "UTF8") + "&";
    url2 += "wresult=" + URLEncoder.encode(wresult, "UTF8");

    webClient2.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage2 = webClient2.getPage(url2);
    webClient2.getOptions().setJavaScriptEnabled(true);
    Assert.assertEquals("IDP SignIn Response Form", idpPage2.getTitleText());

    // Now redirect back to the RP
    final HtmlForm form2 = idpPage2.getFormByName("signinresponseform");

    final HtmlSubmitInput button2 = form2.getInputByName("_eventId_submit");

    final HtmlPage rpPage = button2.click();
    Assert.assertEquals("WS Federation Systests Examples", rpPage.getTitleText());

    webClient2.close();
    return rpPage.getBody().getTextContent();
}
 
Example #27
Source File: SpringTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testNoRequestValidation() throws Exception {

    String url = "https://localhost:" + getRpHttpsPort()
            + "/fedizhelloworldspringnoreqvalidation/secure/fedservlet";
    String user = "alice";
    String password = "ecila";

    // Get the initial token
    CookieManager cookieManager = new CookieManager();
    final WebClient webClient = new WebClient();
    webClient.setCookieManager(cookieManager);
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(user, password));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);
    webClient.getOptions().setJavaScriptEnabled(true);
    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    // Parse the form to remove the context
    DomNodeList<DomElement> results = idpPage.getElementsByTagName("input");

    for (DomElement result : results) {
        if (getContextName().equals(result.getAttributeNS(null, "name"))) {
            result.setAttributeNS(null, "value", "");
        }
    }

    // Invoke back on the RP

    final HtmlForm form = idpPage.getFormByName(getLoginFormName());
    final HtmlSubmitInput button = form.getInputByName("_eventId_submit");

    final HtmlPage rpPage = button.click();
    Assert.assertTrue("WS Federation Systests Examples".equals(rpPage.getTitleText())
                      || "WS Federation Systests Spring Examples".equals(rpPage.getTitleText()));

    webClient.close();

}
 
Example #28
Source File: AbstractClientCertTests.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testDifferentClientCertificate() throws Exception {
    // Get the initial wresult from the IdP
    String url = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";

    CookieManager cookieManager = new CookieManager();
    final WebClient webClient = new WebClient();
    webClient.setCookieManager(cookieManager);
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getOptions().setSSLClientCertificate(
        this.getClass().getClassLoader().getResource("alice_client.jks"), "storepass", "jks");

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);
    webClient.getOptions().setJavaScriptEnabled(true);
    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    // Test the Subject Confirmation method here
    DomNodeList<DomElement> results = idpPage.getElementsByTagName("input");

    String wresult = null;
    String wa = "wsignin1.0";
    String wctx = null;
    String wtrealm = null;
    for (DomElement result : results) {
        if ("wresult".equals(result.getAttributeNS(null, "name"))) {
            wresult = result.getAttributeNS(null, "value");
        } else if ("wctx".equals(result.getAttributeNS(null, "name"))) {
            wctx = result.getAttributeNS(null, "value");
        } else if ("wtrealm".equals(result.getAttributeNS(null, "name"))) {
            wtrealm = result.getAttributeNS(null, "value");
        }
    }
    Assert.assertTrue(wctx != null && wtrealm != null);
    Assert.assertTrue(wresult != null
        && wresult.contains("urn:oasis:names:tc:SAML:2.0:cm:holder-of-key"));
    webClient.close();

    // Now invoke on the RP using the saved parameters above, but a different client cert!
    final WebClient webClient2 = new WebClient();
    webClient2.setCookieManager(cookieManager);
    webClient2.getOptions().setUseInsecureSSL(true);
    webClient2.getOptions().setSSLClientCertificate(
        this.getClass().getClassLoader().getResource("server.jks"), "tompass", "jks");

    WebRequest request = new WebRequest(new URL(url), HttpMethod.POST);

    request.setRequestParameters(new ArrayList<NameValuePair>());
    request.getRequestParameters().add(new NameValuePair("wctx", wctx));
    request.getRequestParameters().add(new NameValuePair("wa", wa));
    request.getRequestParameters().add(new NameValuePair("wtrealm", wtrealm));
    request.getRequestParameters().add(new NameValuePair("wresult", wresult));

    try {
        webClient2.getPage(request);
        Assert.fail("Exception expected");
    } catch (FailingHttpStatusCodeException ex) {
        // expected
        Assert.assertTrue(401 == ex.getStatusCode() || 403 == ex.getStatusCode());
    }

    webClient2.close();
}
 
Example #29
Source File: AbstractClientCertTests.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testClientAuthentication() throws Exception {
    String url = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getOptions().setSSLClientCertificate(
        this.getClass().getClassLoader().getResource("alice_client.jks"), "storepass", "jks");

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);
    webClient.getOptions().setJavaScriptEnabled(true);
    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    final HtmlForm form = idpPage.getFormByName("signinresponseform");
    final HtmlSubmitInput button = form.getInputByName("_eventId_submit");

    // Test the Subject Confirmation method here
    DomNodeList<DomElement> results = idpPage.getElementsByTagName("input");

    String wresult = null;
    for (DomElement result : results) {
        if ("wresult".equals(result.getAttributeNS(null, "name"))) {
            wresult = result.getAttributeNS(null, "value");
            break;
        }
    }
    Assert.assertTrue(wresult != null
        && wresult.contains("urn:oasis:names:tc:SAML:2.0:cm:holder-of-key"));

    final HtmlPage rpPage = button.click();
    Assert.assertTrue("WS Federation Systests Examples".equals(rpPage.getTitleText())
                      || "WS Federation Systests Spring Examples".equals(rpPage.getTitleText()));

    final String bodyTextContent = rpPage.getBody().getTextContent();
    String user = "alice";
    Assert.assertTrue("Principal not " + user,
                      bodyTextContent.contains("userPrincipal=" + user));
    Assert.assertTrue("User " + user + " does not have role Admin",
                      bodyTextContent.contains("role:Admin=false"));
    Assert.assertTrue("User " + user + " does not have role Manager",
                      bodyTextContent.contains("role:Manager=false"));
    Assert.assertTrue("User " + user + " must have role User",
                      bodyTextContent.contains("role:User=true"));

    String claim = ClaimTypes.FIRSTNAME.toString();
    Assert.assertTrue("User " + user + " claim " + claim + " is not 'Alice'",
                      bodyTextContent.contains(claim + "=Alice"));
    claim = ClaimTypes.LASTNAME.toString();
    Assert.assertTrue("User " + user + " claim " + claim + " is not 'Smith'",
                      bodyTextContent.contains(claim + "=Smith"));
    claim = ClaimTypes.EMAILADDRESS.toString();
    Assert.assertTrue("User " + user + " claim " + claim + " is not '[email protected]'",
                      bodyTextContent.contains(claim + "[email protected]"));

    webClient.close();
}
 
Example #30
Source File: AbstractTests.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@Test
public void testEntityExpansionAttack2() throws Exception {

    String url = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
    String user = "alice";
    String password = "ecila";

    // Get the initial token
    CookieManager cookieManager = new CookieManager();
    final WebClient webClient = new WebClient();
    webClient.setCookieManager(cookieManager);
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(user, password));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);
    webClient.getOptions().setJavaScriptEnabled(true);
    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    // Parse the form to get the token (wresult)
    DomNodeList<DomElement> results = idpPage.getElementsByTagName("input");

    String entity = getResourceAsString("/entity2.xml");
    String reference = "&m;";

    for (DomElement result : results) {
        if (getTokenName().equals(result.getAttributeNS(null, "name"))) {
            // Now modify the Signature
            String value = result.getAttributeNS(null, "value");

            if (isWSFederation()) {
                value = entity + value;
                value = value.replace("alice", reference);
                result.setAttributeNS(null, "value", value);
            } else {
                // Decode response
                byte[] deflatedToken = Base64Utility.decode(value);
                InputStream inputStream = new ByteArrayInputStream(deflatedToken);

                Document responseDoc = StaxUtils.read(new InputStreamReader(inputStream, "UTF-8"));

                // Modify SignatureValue to include the entity
                String signatureNamespace = "http://www.w3.org/2000/09/xmldsig#";
                Node signatureValue =
                    responseDoc.getElementsByTagNameNS(signatureNamespace, "SignatureValue").item(0);
                signatureValue.setTextContent(reference + signatureValue.getTextContent());

                // Re-encode response
                String responseMessage = DOM2Writer.nodeToString(responseDoc);
                result.setAttributeNS(null, "value", Base64Utility.encode((entity + responseMessage).getBytes()));
            }
        }
    }

    // Invoke back on the RP

    final HtmlForm form = idpPage.getFormByName(getLoginFormName());
    final HtmlSubmitInput button = form.getInputByName("_eventId_submit");

    try {
        button.click();
        Assert.fail("Failure expected on an entity expansion attack");
    } catch (FailingHttpStatusCodeException ex) {
        // expected
        Assert.assertTrue(401 == ex.getStatusCode() || 403 == ex.getStatusCode());
    }

    webClient.close();
}