Java Code Examples for com.gargoylesoftware.htmlunit.WebClient#getPage()

The following examples show how to use com.gargoylesoftware.htmlunit.WebClient#getPage() . 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: DomTextTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void asXml() throws Exception {
    final String unicodeString = "\u064A\u0627 \u0644\u064A\u064A\u0644";
    final String html = "<html>\n"
        + "<head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'></head>\n"
        + "<body><span id='foo'>" + unicodeString + "</span></body></html>";

    final int[] expectedValues = {1610, 1575, 32, 1604, 1610, 1610, 1604};

    final WebClient client = getWebClient();
    final MockWebConnection webConnection = new MockWebConnection();

    webConnection.setDefaultResponse(TextUtils.stringToByteArray(html, UTF_8), 200, "OK", MimeType.TEXT_HTML);
    client.setWebConnection(webConnection);

    final HtmlPage page = client.getPage(URL_FIRST);
    final String xml = page.getHtmlElementById("foo").getFirstChild().asXml().trim();
    assertEquals(expectedValues.length, xml.length());
    int index = 0;
    for (final int expectedValue : expectedValues) {
        assertEquals(expectedValue, xml.codePointAt(index++));
    }
}
 
Example 2
Source File: HtmlAnchor2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Tests the 'Referer' HTTP header.
 * @throws Exception on test failure
 */
@Test
public void click_refererHeader() throws Exception {
    final String firstContent
        = "<html><head><title>Page A</title></head>\n"
        + "<body><a href='" + URL_SECOND + "' id='link'>link</a></body>\n"
        + "</html>";
    final String secondContent
        = "<html><head><title>Page B</title></head>\n"
        + "<body></body>\n"
        + "</html>";

    final WebClient client = getWebClient();
    final MockWebConnection conn = new MockWebConnection();
    conn.setResponse(URL_FIRST, firstContent);
    conn.setResponse(URL_SECOND, secondContent);
    client.setWebConnection(conn);
    final HtmlPage firstPage = client.getPage(URL_FIRST);
    final HtmlAnchor a = firstPage.getHtmlElementById("link");
    a.click();

    final Map<String, String> lastAdditionalHeaders = conn.getLastAdditionalHeaders();
    assertEquals(URL_FIRST.toString(), lastAdditionalHeaders.get(HttpHeader.REFERER));
}
 
Example 3
Source File: SimpleServletServerTest.java    From wildfly-samples with MIT License 5 votes vote down vote up
@Test
public void testMyAnotherServlet() throws IOException, ServletException {
    SimpleServletServer server = new SimpleServletServer();
    server.start();
    WebClient webClient = new WebClient();
    TextPage page = webClient.getPage(BASE + "/MyAnotherServlet");
    assertEquals("Howdy World from GET", page.getContent());
    
    WebRequest request = new WebRequest(new URL(BASE + "/MyAnotherServlet"), HttpMethod.POST);
    page = webClient.getPage(request);
    assertEquals("Howdy World from POST", page.getContent());
    server.stop();
}
 
Example 4
Source File: XMLHttpRequest3Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Regression test for bug 1209686 (onreadystatechange not called with partial data when emulating FF).
 * @throws Exception if an error occurs
 */
@Test
@NotYetImplemented
public void streaming() throws Exception {
    final Map<String, Class<? extends Servlet>> servlets = new HashMap<>();
    servlets.put("/test", StreamingServlet.class);

    final String resourceBase = "./src/test/resources/com/gargoylesoftware/htmlunit/javascript/host";
    startWebServer(resourceBase, null, servlets);
    final WebClient client = getWebClient();
    final HtmlPage page = client.getPage(URL_FIRST + "XMLHttpRequestTest_streaming.html");
    assertEquals(0, client.waitForBackgroundJavaScriptStartingBefore(1000));
    final HtmlElement body = page.getBody();
    assertEquals(10, body.asText().split("\n").length);
}
 
Example 5
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testBadWa() throws Exception {
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
    url += "wa=wsignin2.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);
    try {
        webClient.getPage(url);
        Assert.fail("Failure expected on a bad wa value");
    } catch (FailingHttpStatusCodeException ex) {
        Assert.assertEquals(ex.getStatusCode(), 400);
    }

    webClient.close();
}
 
Example 6
Source File: WindowTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void status() throws Exception {
    final WebClient webClient = getWebClient();
    final MockWebConnection webConnection = new MockWebConnection();

    final String firstContent
        = "<html><head><title>First</title><script>\n"
        + "function doTest() {\n"
        + "  alert(window.status);\n"
        + "  window.status = 'newStatus';\n"
        + "  alert(window.status);\n"
        + "}\n"
        + "</script></head><body onload='doTest()'>\n"
        + "</body></html>";

    final URL url = URL_FIRST;
    webConnection.setResponse(url, firstContent);
    webClient.setWebConnection(webConnection);

    final List<String> collectedAlerts = new ArrayList<>();
    webClient.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    final List<String> collectedStatus = new ArrayList<>();
    webClient.setStatusHandler(new StatusHandler() {
        @Override
        public void statusMessageChanged(final Page page, final String message) {
            collectedStatus.add(message);
        }
    });
    final HtmlPage firstPage = webClient.getPage(URL_FIRST);
    assertEquals("First", firstPage.getTitleText());

    final String[] expectedAlerts = {"", "newStatus"};
    assertEquals("alerts", expectedAlerts, collectedAlerts);

    final String[] expectedStatus = {"newStatus"};
    assertEquals("status", expectedStatus, collectedStatus);
}
 
Example 7
Source File: ActiveXObjectTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void method() throws Exception {
    if (!getBrowserVersion().isIE()) {
        return;
    }
    if (!isJacobInstalled()) {
        return;
    }
    final String html = "<html><head><title>foo</title><script>\n"
        + "  function test() {\n"
        + "    try {\n"
        + "      var ie = new ActiveXObject('InternetExplorer.Application');\n"
        + "      ie.PutProperty('Hello', 'There');\n"
        + "      alert(ie.GetProperty('Hello'));\n"
        + "    } catch(e) {alert('exception: ' + e.message);}\n"
        + "  }\n"
        + "</script></head><body onload='test()'>\n"
        + "</body></html>";

    final String[] expectedAlerts = {"There"};
    createTestPageForRealBrowserIfNeeded(html, expectedAlerts);

    final WebClient client = getWebClient();
    client.getOptions().setActiveXNative(true);
    final List<String> collectedAlerts = new ArrayList<>();
    client.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    final MockWebConnection webConnection = new MockWebConnection();
    webConnection.setResponse(URL_FIRST, html);
    client.setWebConnection(webConnection);

    client.getPage(URL_FIRST);
    assertEquals(expectedAlerts, collectedAlerts);
}
 
Example 8
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testUnknownRACS() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/"
        + getServletContextName() + "/insecure/fedservlet";
    AuthnRequest authnRequest =
        new DefaultAuthnRequestBuilder().createAuthnRequest(
            null, "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL
        );
    authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");
    signAuthnRequest(authnRequest);

    String authnRequestEncoded = encodeAuthnRequest(authnRequest);

    String relayState = UUID.randomUUID().toString();
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml?"
            + SSOConstants.RELAY_STATE + "=" + relayState
            + "&" + SSOConstants.SAML_REQUEST + "=" + URLEncoder.encode(authnRequestEncoded, UTF_8.name());

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

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);

    org.opensaml.saml.saml2.core.Response samlResponse =
        parseSAMLResponse(idpPage, relayState, consumerURL, authnRequest.getID());
    String expected = "urn:oasis:names:tc:SAML:2.0:status:Requester";
    Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue());

    webClient.close();
}
 
Example 9
Source File: HtmlAnchor2Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void clickShift() throws Exception {
    final String first
        = "<html><head><title>First</title></head><body>\n"
        + "  <a href='" + URL_SECOND + "' id='a2'>link to foo2</a>\n"
        + "</body></html>";
    final String second
        = "<html><head><title>Second</title></head><body></body></html>";

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

    final MockWebConnection webConnection = new MockWebConnection();
    webConnection.setResponse(URL_FIRST, first);
    webConnection.setResponse(URL_SECOND, second);
    client.setWebConnection(webConnection);

    assertEquals(1, getWebClient().getTopLevelWindows().size());
    final HtmlPage page = client.getPage(URL_FIRST);
    final HtmlAnchor anchor = page.getHtmlElementById("a2");

    final HtmlPage secondPage = anchor.click(true, false, false);
    assertEquals(2, getWebClient().getTopLevelWindows().size());
    assertEquals("Second", secondPage.getTitleText());
}
 
Example 10
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testLargeQueryParameterRejected() 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";

    StringBuilder sb = new StringBuilder("https://localhost:" + getRpHttpsPort() + "/"
            + getServletContextName() + "/secure/fedservlet");
    for (int i = 0; i < 100; i++) {
        sb.append("aaaaaaaaaa");
    }

    url += "&wreply=" + sb.toString();

    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);
    try {
        webClient.getPage(url);
        Assert.fail("Failure expected on a bad wreply value");
    } catch (FailingHttpStatusCodeException ex) {
        Assert.assertEquals(ex.getStatusCode(), 400);
    }

    webClient.close();
}
 
Example 11
Source File: HtmlFileInput2Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Tests setData method.
 * @throws Exception if the test fails
 */
@Test
public void setValueAttributeAndSetDataDummyFile() throws Exception {
    final String firstContent = "<html><head></head><body>\n"
        + "<form enctype='multipart/form-data' action='" + URL_SECOND + "' method='POST'>\n"
        + "  <input type='file' name='image'>\n"
        + "  <input type='submit' id='mySubmit'>\n"
        + "</form>\n"
        + "</body>\n"
        + "</html>";
    final String secondContent = "<html><head><title>second</title></head></html>";
    final WebClient client = getWebClient();

    final MockWebConnection webConnection = new MockWebConnection();
    webConnection.setResponse(URL_FIRST, firstContent);
    webConnection.setResponse(URL_SECOND, secondContent);

    client.setWebConnection(webConnection);

    final HtmlPage firstPage = client.getPage(URL_FIRST);
    final HtmlForm f = firstPage.getForms().get(0);
    final HtmlFileInput fileInput = f.getInputByName("image");
    fileInput.setValueAttribute("dummy.txt");
    fileInput.setContentType("text/csv");
    fileInput.setData("My file data".getBytes());
    firstPage.getHtmlElementById("mySubmit").click();
    final KeyDataPair pair = (KeyDataPair) webConnection.getLastParameters().get(0);

    assertNotNull(pair.getData());
    assertTrue(pair.getData().length > 10);

    final HttpEntity httpEntity = post(client, webConnection);

    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        httpEntity.writeTo(out);

        assertTrue(out.toString().contains(
                "Content-Disposition: form-data; name=\"image\"; filename=\"dummy.txt\""));
    }
}
 
Example 12
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 13
Source File: JavascriptErrorListenerTest.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * Test for running without a JavaScript error listener.
 *
 * @throws Exception if the test fails
 */
@Test
public void nullJavaScriptErrorListener() throws Exception {
    final WebClient webClient = getWebClient();
    webClient.getOptions().setThrowExceptionOnScriptError(false);
    webClient.setJavaScriptErrorListener(null);
    final MockWebConnection webConnection = new MockWebConnection();
    final String errorContent = "<html><head><title>ERROR 500</title></head><body></body></html>";
    final List<NameValuePair> emptyList = Collections.emptyList();
    webConnection.setResponse(URL_SECOND, errorContent, 500, "BOOM", MimeType.TEXT_HTML, emptyList);

    // test script exception
    String content = "<html><head><title>Throw JavaScript Error</title>\n"
        + "<script>unknown.foo();</script></head>\n"
        + "<body></body></html>";
    webConnection.setResponse(URL_FIRST, content);
    webClient.setWebConnection(webConnection);
    webClient.getPage(URL_FIRST);

    // test load script error
    content = "<html><head><title>Throw JavaScript Error</title>\n"
        + "<script src='" + URL_SECOND + "' type='text/javascript'></script></head>\n"
        + "<body></body></html>";
    webConnection.setResponse(URL_FIRST, content);
    try {
        webClient.getPage(URL_FIRST);
        fail("FailingHttpStatusCodeException expected");
    }
    catch (final FailingHttpStatusCodeException e) {
        // expected
    }

    // test malformed script url error
    content = "<html><head><title>Throw JavaScript Error</title>\n"
        + "<script src='unknown://nowhere' type='text/javascript'></script></head>\n"
        + "<body></body></html>";
    webConnection.setResponse(URL_FIRST, content);
    webClient.getPage(URL_FIRST);

    // test timeout error
    webClient.setJavaScriptTimeout(100);

    content = "<html><head><title>Throw JavaScript Timeout Error</title>\n"
        + "<script>while(1) {}</script></head>\n"
        + "<body></body></html>";
    webConnection.setResponse(URL_FIRST, content);
    webClient.getPage(URL_FIRST);
}
 
Example 14
Source File: AbstractExpiryTests.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@Test
public void testPluginTokenExpiry() throws Exception {
    String url = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName()
        + "/secure/fedservlet";
    String user = "alice";
    String password = "ecila";

    // 1. Login
    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);
    HtmlPage idpPage = webClient.getPage(url);
    webClient.getOptions().setJavaScriptEnabled(true);
    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

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

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

    String bodyTextContent = rpPage.getBody().getTextContent();
    verifyApplication(user, bodyTextContent);

    // 2. Sleep to expire the token
    System.out.println("Sleeping...");
    Thread.sleep(8L * 1000L);

    // 3. Now invoke again on the endpoint
    webClient.getOptions().setJavaScriptEnabled(false);
    idpPage = webClient.getPage(url);
    webClient.getOptions().setJavaScriptEnabled(true);
    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

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

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

    bodyTextContent = rpPage.getBody().getTextContent();
    verifyApplication(user, bodyTextContent);

    webClient.close();
}
 
Example 15
Source File: HtmlPage2Test.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("25")
public void loadExternalJavaScript() throws Exception {
    final String html =
        "<html><head>\n"
        + "<script>\n"
        + "function makeIframe() {\n"
        + "  var iframesrc = '<html><head>';\n"
        + "  iframesrc += '<script src=\"" + "js.js" + "\"></' + 'script>';\n"
        + "  iframesrc += '<script>';\n"
        + "  iframesrc += 'function doSquared() {';\n"
        + "  iframesrc += '    try {';\n"
        + "  iframesrc += '      var y = squared(5);';\n"
        + "  iframesrc += '      alert(y);';\n"
        + "  iframesrc += '    } catch (e) {';\n"
        + "  iframesrc += '      alert(\"error\");';\n"
        + "  iframesrc += '    }';\n"
        + "  iframesrc += '}';\n"
        + "  iframesrc += '</' + 'script>';\n"
        + "  iframesrc += '</head>';\n"
        + "  iframesrc += '<body onLoad=\"doSquared()\" >';\n"
        + "  iframesrc += '</body>';\n"
        + "  iframesrc += '</html>';\n"
        + "  var iframe = document.createElement('IFRAME');\n"
        + "  iframe.id = 'iMessage';\n"
        + "  iframe.name = 'iMessage';\n"
        + "  iframe.src = \"javascript:'\" + iframesrc + \"'\";\n"
        + "  document.body.appendChild(iframe);\n"
        + "}\n"
        + "</script></head>\n"
        + "<body onload='makeIframe()'>\n"
        + "</body></html>";

    final String js = "function squared(n) {return n * n}";

    final WebClient webClient = getWebClient();
    final MockWebConnection webConnection = new MockWebConnection();

    webConnection.setResponse(URL_FIRST, html);
    webConnection.setResponse(new URL(URL_FIRST, "js.js"), js);
    webClient.setWebConnection(webConnection);

    final List<String> collectedAlerts = new ArrayList<>();
    webClient.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    webClient.getPage(URL_FIRST);
    assertEquals(getExpectedAlerts(), collectedAlerts);
}
 
Example 16
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testBadIssuerFormat() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/"
        + getServletContextName() + "/secure/fedservlet";

    String issuerId = "urn:org:apache:cxf:fediz:fedizhelloworld";
    Issuer issuer =
        SamlpRequestComponentBuilder.createIssuer(issuerId);
    issuer.setFormat("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress");

    String nameIDFormat = "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent";
    NameIDPolicy nameIDPolicy =
        SamlpRequestComponentBuilder.createNameIDPolicy(true, nameIDFormat, issuerId);

    AuthnContextClassRef authnCtxClassRef =
        SamlpRequestComponentBuilder.createAuthnCtxClassRef(
            "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"
        );
    RequestedAuthnContext authnCtx =
        SamlpRequestComponentBuilder.createRequestedAuthnCtxPolicy(
            AuthnContextComparisonTypeEnumeration.EXACT,
            Collections.singletonList(authnCtxClassRef), null
        );

    String protocolBinding = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST";
    AuthnRequest authnRequest = SamlpRequestComponentBuilder.createAuthnRequest(
            consumerURL,
            false,
            false,
            protocolBinding,
            SAMLVersion.VERSION_20,
            issuer,
            nameIDPolicy,
            authnCtx
    );

    authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");
    signAuthnRequest(authnRequest);

    String authnRequestEncoded = encodeAuthnRequest(authnRequest);

    String relayState = UUID.randomUUID().toString();
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml?"
            + SSOConstants.RELAY_STATE + "=" + relayState
            + "&" + SSOConstants.SAML_REQUEST + "=" + URLEncoder.encode(authnRequestEncoded, UTF_8.name());

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

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);

    org.opensaml.saml.saml2.core.Response samlResponse =
        parseSAMLResponse(idpPage, relayState, consumerURL, authnRequest.getID());
    String expected = "urn:oasis:names:tc:SAML:2.0:status:Requester";
    Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue());

    webClient.close();
}
 
Example 17
Source File: HolderOfKeyTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testHolderOfKey() 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.getOptions().setSSLClientCertificate(
        this.getClass().getClassLoader().getResource("client.jks"), "storepass", "jks");
    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");

    // 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.assertEquals("WS Federation Systests Examples", rpPage.getTitleText());

    final String bodyTextContent = rpPage.getBody().getTextContent();
    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 18
Source File: HostExtractor.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
private static void fillMDNWebAPI(final WebClient webClient, final Set<String> set) throws Exception {
    final HtmlPage page = webClient.getPage("https://developer.mozilla.org/en-US/docs/Web/API");
    for (final Object o : page.getByXPath("//*[@class='indexListTerm']")) {
        set.add(((HtmlElement) o).asText());
    }
}
 
Example 19
Source File: HtmlFormTest.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * Utility for {@link #submitRequestCharset()}
 * @param headerCharset the charset for the content type header if not null
 * @param metaCharset the charset for the meta http-equiv content type tag if not null
 * @param formCharset the charset for the form's accept-charset attribute if not null
 * @param expectedRequestCharset the charset expected for the form submission
 * @throws Exception if the test fails
 */
private void submitRequestCharset(final String headerCharset,
        final String metaCharset, final String formCharset,
        final Charset expectedRequestCharset) throws Exception {

    final String formAcceptCharset;
    if (formCharset == null) {
        formAcceptCharset = "";
    }
    else {
        formAcceptCharset = " accept-charset='" + formCharset + "'";
    }

    final String metaContentType;
    if (metaCharset == null) {
        metaContentType = "";
    }
    else {
        metaContentType = "<meta http-equiv='Content-Type' content='text/html; charset="
            + metaCharset + "'>\n";
    }

    final String html = "<html><head><title>foo</title>\n"
        + metaContentType
        + "</head><body>\n"
        + "<form name='form1' method='post' action='foo'"
        + formAcceptCharset + ">\n"
        + "<input type='text' name='textField' value='foo'/>\n"
        + "<input type='text' name='nonAscii' value='Flo\u00DFfahrt'/>\n"
        + "<input type='submit' name='button' value='foo'/>\n"
        + "</form></body></html>";
    final WebClient client = getWebClientWithMockWebConnection();
    final MockWebConnection webConnection = getMockWebConnection();

    String contentType = MimeType.TEXT_HTML;
    if (headerCharset != null) {
        contentType += ";charset=" + headerCharset;
    }
    webConnection.setDefaultResponse(html, 200, "ok", contentType);
    final HtmlPage page = client.getPage(URL_FIRST);

    final String firstPageEncoding = StringUtils.defaultString(metaCharset, headerCharset).toUpperCase(Locale.ROOT);
    assertEquals(firstPageEncoding, page.getCharset().name());

    final HtmlForm form = page.getFormByName("form1");
    form.getInputByName("button").click();

    assertSame(expectedRequestCharset, webConnection.getLastWebRequest().getCharset());
}
 
Example 20
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();
}