com.gargoylesoftware.htmlunit.html.HtmlSubmitInput Java Examples

The following examples show how to use com.gargoylesoftware.htmlunit.html.HtmlSubmitInput. 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: HTMLFormElement2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
* @throws Exception if the test fails
*/
@Test
@Alerts("hi!")
public void lostFunction() throws Exception {
    final String content
        = "<html><head><title>foo</title><script>\n"
        + " function onSubmit() { alert('hi!'); return false; }\n"
        + "</script></head><body>\n"
        + "<form onsubmit='return onSubmit();'>\n"
        + "  <input type='submit' id='clickMe' />\n"
        + "</form>\n"
        + "</body></html>";

    final List<String> collectedAlerts = new ArrayList<>();
    final HtmlPage page = loadPage(content, collectedAlerts);
    final HtmlSubmitInput button = page.getHtmlElementById("clickMe");
    button.click();
    assertEquals(getExpectedAlerts(), collectedAlerts);
}
 
Example #2
Source File: HtmlUnitAndSpringLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenAMessage_whenSent_thenItShows() throws Exception {
    String text = "Hello world!";
    HtmlPage page;

    String url = "http://localhost/message/showForm";
    page = webClient.getPage(url);

    HtmlTextInput messageText = page.getHtmlElementById("message");
    messageText.setValueAttribute(text);

    HtmlForm form = page.getForms().get(0);
    HtmlSubmitInput submit = form.getOneHtmlElementByAttribute("input", "type", "submit");
    HtmlPage newPage = submit.click();

    String receivedText = newPage.getHtmlElementById("received").getTextContent();

    Assert.assertEquals(receivedText, text);
}
 
Example #3
Source File: HTTPTestUtils.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
public static String loginWithCookieManager(String url, String user, String password, String idpPort,
        String formName, CookieManager cookieManager) throws IOException {
    final WebClient webClient = new WebClient();
    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());

    final HtmlForm form = idpPage.getFormByName(formName);
    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();
    return rpPage.getBody().getTextContent();
}
 
Example #4
Source File: HTTPTestUtils.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
public static String login(String url, String user, String password, String idpPort,
                           String formName) 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());

    final HtmlForm form = idpPage.getFormByName(formName);
    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();
    return rpPage.getBody().getTextContent();
}
 
Example #5
Source File: AbstractOIDCTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private static <P extends Page> P login(final UriBuilder uriBuilder, final WebClient webClient)
    throws IOException {
    final HtmlPage idpPage = webClient.getPage(
        uriBuilder.queryParam("login_hint", "blabla@" + HOME_REALM).build().toURL());
    assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    webClient.getCredentialsProvider().clear();

    // Test the SAML Version here
    String wresult = null;
    for (DomElement result : idpPage.getElementsByTagName("input")) {
        if ("wresult".equals(result.getAttributeNS(null, "name"))) {
            wresult = result.getAttributeNS(null, "value");
            assertTrue(wresult.contains("urn:oasis:names:tc:SAML:2.0:cm:bearer"));
            break;
        }
    }
    assertNotNull(wresult);

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

    return button.click();
}
 
Example #6
Source File: CsrfIT.java    From ozark with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves a form, removes CSRF hidden field and attempts to submit. Should
 * result in a 403 error.
 *
 * @throws Exception an error occurs or validation fails.
 */
@Test
public void testFormFail() throws Exception {
    HtmlPage page1 = webClient.getPage(webUrl + "resources/csrf");
    HtmlForm form = (HtmlForm) page1.getDocumentElement().getHtmlElementsByTagName("form").get(0);

    // Remove hidden input field to cause a CSRF validation failure
    HtmlElement input = form.getHtmlElementsByTagName("input").get(1);
    form.removeChild(input);

    // Submit form - should fail
    HtmlSubmitInput button = (HtmlSubmitInput) form.getHtmlElementsByTagName("input").get(0);
    try {
        button.click();
        fail("CSRF validation should have failed!");
    } catch (FailingHttpStatusCodeException e) {
        // falls through
    }
}
 
Example #7
Source File: CsrfIT.java    From ozark with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve a form and submit it making sure the CSRF hidden field is present
 *
 * @throws Exception an error occurs or validation fails.
 */
@Test
public void testFormOk() throws Exception {
    HtmlPage page1 = webClient.getPage(webUrl + "resources/csrf");
    HtmlForm form = (HtmlForm) page1.getDocumentElement().getHtmlElementsByTagName("form").get(0);

    // Check hidden input field
    HtmlElement input = form.getHtmlElementsByTagName("input").get(1);
    assertTrue(input.getAttribute("type").equals("hidden"));
    assertTrue(input.getAttribute("name").equals(CSRF_PARAM));
    assertTrue(input.hasAttribute("value"));        // token

    // Submit form
    HtmlSubmitInput button = (HtmlSubmitInput) form.getHtmlElementsByTagName("input").get(0);
    HtmlPage page2 = button.click();
    Iterator<HtmlElement> it = page2.getDocumentElement().getHtmlElementsByTagName("h1").iterator();
    assertTrue(it.next().asText().contains("CSRF Protection OK"));
}
 
Example #8
Source File: CsrfIT.java    From ozark with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves a form, removes CSRF hidden field and attempts to submit. Should
 * result in a 403 error.
 *
 * @throws Exception an error occurs or validation fails.
 */
@Test
public void testFormFail() throws Exception {
    HtmlPage page1 = webClient.getPage(webUrl + "resources/csrf");
    HtmlForm form = (HtmlForm) page1.getDocumentElement().getHtmlElementsByTagName("form").get(0);

    // Remove hidden input field to cause a CSRF validation failure
    HtmlElement input = form.getHtmlElementsByTagName("input").get(1);
    form.removeChild(input);

    // Submit form - should fail
    HtmlSubmitInput button = (HtmlSubmitInput) form.getHtmlElementsByTagName("input").get(0);
    try {
        button.click();
        fail("CSRF validation should have failed!");
    } catch (FailingHttpStatusCodeException e) {
        // falls through
    }
}
 
Example #9
Source File: CsrfIT.java    From ozark with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve a form and submit it making sure the CSRF hidden field is present
 *
 * @throws Exception an error occurs or validation fails.
 */
@Test
public void testFormOk() throws Exception {
    HtmlPage page1 = webClient.getPage(webUrl + "resources/csrf");
    HtmlForm form = (HtmlForm) page1.getDocumentElement().getHtmlElementsByTagName("form").get(0);

    // Check hidden input field
    HtmlElement input = form.getHtmlElementsByTagName("input").get(1);
    assertTrue(input.getAttribute("type").equals("hidden"));
    assertTrue(input.getAttribute("name").equals(CSRF_PARAM));
    assertTrue(input.hasAttribute("value"));        // token

    // Submit form
    HtmlSubmitInput button = (HtmlSubmitInput) form.getHtmlElementsByTagName("input").get(0);
    HtmlPage page2 = button.click();
    Iterator<HtmlElement> it = page2.getDocumentElement().getHtmlElementsByTagName("h1").iterator();
    assertTrue(it.next().asText().contains("CSRF Protection OK"));
}
 
Example #10
Source File: HTMLFormElement2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("hi!")
public void assignedOnsubmit() throws Exception {
    final String content
        = "<html><head><title>foo</title><script>\n"
        + "  function onSubmit() { alert('hi!'); return false; }\n"
        + "  function init() { document.myForm.onsubmit = onSubmit; }\n"
        + "  window.onload = init;\n"
        + "</script></head><body>\n"
        + "<form name='myForm'>\n"
        + "  <input type='submit' id='clickMe' />\n"
        + "</form>\n"
        + "</body></html>";

    final List<String> collectedAlerts = new ArrayList<>();
    final HtmlPage page = loadPage(content, collectedAlerts);
    final HtmlSubmitInput button = page.getHtmlElementById("clickMe");
    button.click();
    assertEquals(getExpectedAlerts(), collectedAlerts);
}
 
Example #11
Source File: CsrfIT.java    From krazo with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve a form and submit it making sure the CSRF hidden field is present
 *
 * @throws Exception an error occurs or validation fails.
 */
@Test
public void testFormOk() throws Exception {
    HtmlPage page1 = webClient.getPage(webUrl + "resources/csrf");
    HtmlForm form = (HtmlForm) page1.getDocumentElement().getElementsByTagName("form").get(0);

    // Check hidden input field
    HtmlElement input = form.getElementsByTagName("input").get(1);
    assertTrue(input.getAttribute("type").equals("hidden"));
    assertTrue(input.getAttribute("name").equals(CSRF_PARAM));
    assertTrue(input.hasAttribute("value"));        // token

    // Submit form
    HtmlSubmitInput button = (HtmlSubmitInput) form.getElementsByTagName("input").get(0);
    HtmlPage page2 = button.click();
    Iterator<HtmlElement> it = page2.getDocumentElement().getElementsByTagName("h1").iterator();
    assertTrue(it.next().asText().contains("CSRF Protection OK"));
}
 
Example #12
Source File: CsrfIT.java    From krazo with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves a form, removes CSRF hidden field and attempts to submit. Should
 * result in a 403 error.
 *
 * @throws Exception an error occurs or validation fails.
 */
@Test
public void testFormFail() throws Exception {
    HtmlPage page1 = webClient.getPage(webUrl + "resources/csrf");
    HtmlForm form = (HtmlForm) page1.getDocumentElement().getElementsByTagName("form").get(0);

    // Remove hidden input field to cause a CSRF validation failure
    HtmlElement input = form.getElementsByTagName("input").get(1);
    form.removeChild(input);

    // Submit form - should fail
    HtmlSubmitInput button = (HtmlSubmitInput) form.getElementsByTagName("input").get(0);
    try {
        button.click();
        fail("CSRF validation should have failed!");
    } catch (FailingHttpStatusCodeException e) {
        // falls through
    }
}
 
Example #13
Source File: CsrfValidateFilterIT.java    From krazo with Apache License 2.0 5 votes vote down vote up
@Test
public void testPostWithoutCsrfFieldFailsWithStatusCode403() throws Exception {
    final HtmlPage page1 = webClient.getPage(baseURL + "resources/csrf-methods/exception-post");
    final HtmlForm form = (HtmlForm) page1.getElementById("form");
    final HtmlSubmitInput button = form.getInputByName("submit");

    final Page result = button.click();

    assertEquals(403, result.getWebResponse()
        .getStatusCode());
}
 
Example #14
Source File: XMLHttpRequest3Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Test for a strange error we found: An ajax running
 * in parallel shares the additional headers with a form
 * submit.
 *
 * @throws Exception if an error occurs
 */
@Test
public void ajaxInfluencesSubmitHeaders() throws Exception {
    final Map<String, Class<? extends Servlet>> servlets = new HashMap<>();
    servlets.put("/content.html", ContentServlet.class);
    servlets.put("/ajax_headers.html", AjaxHeaderServlet.class);
    servlets.put("/form_headers.html", FormHeaderServlet.class);
    startWebServer("./", null, servlets);

    collectedHeaders_.clear();
    XMLHttpRequest3Test.STATE_ = 0;
    final WebClient client = getWebClient();

    final List<String> collectedAlerts = Collections.synchronizedList(new ArrayList<String>());
    client.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    final HtmlPage page = client.getPage(URL_FIRST + "content.html");
    final DomElement elem = page.getElementById("doIt");
    while (STATE_ < 1) {
        Thread.sleep(42);
    }
    ((HtmlSubmitInput) elem).click();

    client.waitForBackgroundJavaScript(DEFAULT_WAIT_TIME);
    assertEquals(collectedHeaders_.toString(), 2, collectedHeaders_.size());

    String headers = collectedHeaders_.get(0);
    if (!headers.startsWith("Form: ")) {
        headers = collectedHeaders_.get(1);
    }
    assertTrue(headers, headers.startsWith("Form: "));
    assertFalse(headers, headers.contains("Html-Unit=is great,;"));

    headers = collectedHeaders_.get(0);
    if (!headers.startsWith("Ajax: ")) {
        headers = collectedHeaders_.get(1);
    }
    assertTrue(headers, headers.startsWith("Ajax: "));
    assertTrue(headers, headers.contains("Html-Unit=is great,;"));
}
 
Example #15
Source File: SAMLSSOTest.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, 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);
    HtmlPage idpPage = webClient.getPage(url);

    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    // Now redirect back to the IdP for Realm A
    HtmlForm form = idpPage.getFormByName("signinresponseform");

    HtmlSubmitInput button = form.getInputByName("_eventId_submit");

    HtmlPage idpPageRealmA = button.click();

    Assert.assertTrue("SAML IDP Response Form".equals(idpPage.getTitleText())
                      || "IDP SignIn Response Form".equals(idpPage.getTitleText()));
    form = idpPageRealmA.getFormByName("samlsigninresponseform");

    // Now redirect back to the SAML SSO web app
    button = form.getInputByName("_eventId_submit");

    XmlPage rpPage = button.click();

    webClient.close();
    return rpPage.asXml();
}
 
Example #16
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 #17
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 #18
Source File: AudienceRestrictionTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testSAMLTokenWithNonMatchingAudienceRestriction() throws Exception {
    String url = "https://localhost:" + TomcatLauncher.getRpHttpsPort() + '/' + SERVLET_CONTEXT_NAME
            + "/secure/fedservlet";
    String user = "alice";
    String password = "ecila";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(TomcatLauncher.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());

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

    try {
        button.click();
        Assert.fail("Failure expected on a bad audience restriction value");
    } catch (FailingHttpStatusCodeException ex) {
        Assert.assertEquals(ex.getStatusCode(), 401);
    }

    webClient.close();
}
 
Example #19
Source File: CsrfValidateFilterIT.java    From krazo with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutWithoutCsrfFieldFailsWithStatusCode403() throws Exception {
    final HtmlPage page1 = webClient.getPage(baseURL + "resources/csrf-methods/exception-put");
    final HtmlForm form = (HtmlForm) page1.getElementById("form");
    final HtmlSubmitInput button = form.getInputByName("submit");

    final Page result = button.click();

    assertEquals(403, result.getWebResponse()
        .getStatusCode());
}
 
Example #20
Source File: CsrfValidateFilterIT.java    From krazo with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutWithCsrfFieldWorksWithStatusCode200() throws Exception {
    final HtmlPage page1 = webClient.getPage(baseURL + "resources/csrf-methods/ok-put");
    final HtmlForm form = (HtmlForm) page1.getElementById("form");
    final HtmlSubmitInput button = form.getInputByName("submit");

    final Page result = button.click();

    assertEquals(200, result.getWebResponse()
        .getStatusCode());
}
 
Example #21
Source File: CsrfValidateFilterIT.java    From krazo with Apache License 2.0 5 votes vote down vote up
@Test
public void testPostWithCsrfFieldWorksWithStatusCode200() throws Exception {
    final HtmlPage page1 = webClient.getPage(baseURL + "resources/csrf-methods/ok-post");
    final HtmlForm form = (HtmlForm) page1.getElementById("form");
    final HtmlSubmitInput button = form.getInputByName("submit");

    final Page result = button.click();

    assertEquals(200, result.getWebResponse()
        .getStatusCode());
}
 
Example #22
Source File: CsrfValidateFilterIT.java    From krazo with Apache License 2.0 5 votes vote down vote up
@Test
public void testPatchWithCsrfFieldWorksWithStatusCode200() throws Exception {
    final HtmlPage page1 = webClient.getPage(baseURL + "resources/csrf-methods/ok-patch");
    final HtmlForm form = (HtmlForm) page1.getElementById("form");
    final HtmlSubmitInput button = form.getInputByName("submit");

    final Page result = button.click();

    assertEquals(200, result.getWebResponse()
        .getStatusCode());
}
 
Example #23
Source File: ConverterPriorityIT.java    From krazo with Apache License 2.0 5 votes vote down vote up
@Test
public void testCorrectCustomConverterIsUsedForDoubleValue() throws Exception {
    final HtmlPage page1 = webClient.getPage(baseURL + "resources/converter");
    final HtmlForm form = (HtmlForm) page1.getElementById("form");
    final HtmlSubmitInput button = form.getInputByName("submit");

    final HtmlPage resultPage = button.click();

    final double result = Double.parseDouble(resultPage.getElementById("result").getTextContent());

    assertEquals(42.0D, result, 0);
}
 
Example #24
Source File: CsrfValidateFilterIT.java    From krazo with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeleteWithCsrfFieldWorksWithStatusCode200() throws Exception {
    final HtmlPage page1 = webClient.getPage(baseURL + "resources/csrf-methods/ok-delete");
    final HtmlForm form = (HtmlForm) page1.getElementById("form");
    final HtmlSubmitInput button = form.getInputByName("submit");

    final Page result = button.click();

    assertEquals(200, result.getWebResponse()
        .getStatusCode());
}
 
Example #25
Source File: CsrfValidateFilterIT.java    From krazo with Apache License 2.0 5 votes vote down vote up
@Test
public void testPatchWithoutCsrfFieldFailsWithStatusCode403() throws Exception {
    final HtmlPage page1 = webClient.getPage(baseURL + "resources/csrf-methods/exception-patch");
    final HtmlForm form = (HtmlForm) page1.getElementById("form");
    final HtmlSubmitInput button = form.getInputByName("submit");

    final Page result = button.click();

    assertEquals(403, result.getWebResponse()
        .getStatusCode());
}
 
Example #26
Source File: CsrfValidateFilterIT.java    From krazo with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeleteWithoutCsrfFieldFailsWithStatusCode403() throws Exception {
    final HtmlPage page1 = webClient.getPage(baseURL + "resources/csrf-methods/exception-delete");
    final HtmlForm form = (HtmlForm) page1.getElementById("form");
    final HtmlSubmitInput button = form.getInputByName("submit");

    final Page result = button.click();

    assertEquals(403, result.getWebResponse()
        .getStatusCode());
}
 
Example #27
Source File: AnnotationDrivenConverterIT.java    From krazo with Apache License 2.0 5 votes vote down vote up
@Test
public void testCorrectCustomConverterIsUsedForDoubleValue() throws Exception {
    final HtmlPage page1 = webClient.getPage(baseURL + "resources/converter-annotations");
    final HtmlForm form = (HtmlForm) page1.getElementById("form");
    final HtmlSubmitInput button = form.getInputByName("submit");

    final HtmlPage resultPage = button.click();

    final double result = Double.parseDouble(resultPage.getElementById("result").getTextContent());

    assertEquals(42.0D, result, 0);
}
 
Example #28
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 #29
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 #30
Source File: WSFedTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private static String loginOIDC(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);

    // The decision page is returned as XML for some reason. So parse it and send a form response back.
    HtmlPage oidcIdpConfirmationPage = webClient.getPage(url);
    final HtmlForm oidcForm = oidcIdpConfirmationPage.getForms().get(0);

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

    request.setRequestParameters(Arrays.asList(
        new NameValuePair("client_id",
            oidcForm.getInputByName("client_id").getValueAttribute()),
        new NameValuePair("redirect_uri",
            oidcForm.getInputByName("redirect_uri").getValueAttribute()),
        new NameValuePair("scope",
            oidcForm.getInputByName("scope").getValueAttribute()),
        new NameValuePair("state",
            oidcForm.getInputByName("state").getValueAttribute()),
        new NameValuePair("session_authenticity_token",
            oidcForm.getInputByName("session_authenticity_token").getValueAttribute()),
        new NameValuePair("oauthDecision", "allow")));

    HtmlPage idpPage = webClient.getPage(request);

    assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

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

    final HtmlSubmitInput button = form.getInputByName("_eventId_submit");

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

    webClient.close();
    return rpPage.getBody().getTextContent();
}