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

The following examples show how to use com.gargoylesoftware.htmlunit.WebClient#setCookieManager() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSuccessfulSSOInvokeOnIdPWithForceAuthn() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/"
        + getServletContextName() + "/secure/fedservlet";
    AuthnRequest authnRequest =
        new DefaultAuthnRequestBuilder().createAuthnRequest(
            null, "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL
        );
    authnRequest.setForceAuthn(Boolean.TRUE);
    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();
    CookieManager cookieManager = new CookieManager();
    webClient.setCookieManager(cookieManager);
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(USER, PWD));

    //
    // First invocation
    //

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

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

    // Check claims
    String parsedResponse = DOM2Writer.nodeToString(samlResponse.getDOM().getOwnerDocument());
    String claim = ClaimTypes.FIRSTNAME.toString();
    Assert.assertTrue(parsedResponse.contains(claim));
    claim = ClaimTypes.LASTNAME.toString();
    Assert.assertTrue(parsedResponse.contains(claim));
    claim = ClaimTypes.EMAILADDRESS.toString();
    Assert.assertTrue(parsedResponse.contains(claim));

    //
    // Second invocation
    //

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

    samlResponse = parseSAMLResponse(idpPage, relayState, consumerURL, authnRequest.getID());
    expected = "urn:oasis:names:tc:SAML:2.0:status:Success";
    Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue());

    // Check claims
    parsedResponse = DOM2Writer.nodeToString(samlResponse.getDOM().getOwnerDocument());
    claim = ClaimTypes.FIRSTNAME.toString();
    Assert.assertTrue(parsedResponse.contains(claim));
    claim = ClaimTypes.LASTNAME.toString();
    Assert.assertTrue(parsedResponse.contains(claim));
    claim = ClaimTypes.EMAILADDRESS.toString();
    Assert.assertTrue(parsedResponse.contains(claim));

    webClient.close();

    //
    // Third invocation - create a new WebClient with no credentials (but with the same CookieManager)
    // ...this should fail
    //

    WebClient newWebClient = new WebClient();
    newWebClient.setCookieManager(cookieManager);
    newWebClient.getOptions().setUseInsecureSSL(true);
    newWebClient.getOptions().setJavaScriptEnabled(false);

    try {
        newWebClient.getPage(url);
        Assert.fail("Failure expected on no credentials");
    }  catch (FailingHttpStatusCodeException ex) {
        Assert.assertEquals(ex.getStatusCode(), 401);
    }

    newWebClient.close();
}
 
Example 8
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();
}
 
Example 9
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 10
Source File: SAMLSSOTest.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(new ArrayList<NameValuePair>());
    String clientId = oidcForm.getInputByName("client_id").getValueAttribute();
    request.getRequestParameters().add(new NameValuePair("client_id", clientId));
    String redirectUri = oidcForm.getInputByName("redirect_uri").getValueAttribute();
    request.getRequestParameters().add(new NameValuePair("redirect_uri", redirectUri));
    String scope = oidcForm.getInputByName("scope").getValueAttribute();
    request.getRequestParameters().add(new NameValuePair("scope", scope));
    String state = oidcForm.getInputByName("state").getValueAttribute();
    request.getRequestParameters().add(new NameValuePair("state", state));
    String authToken = oidcForm.getInputByName("session_authenticity_token").getValueAttribute();
    request.getRequestParameters().add(new NameValuePair("session_authenticity_token", authToken));
    request.getRequestParameters().add(new NameValuePair("oauthDecision", "allow"));

    HtmlPage idpPage = webClient.getPage(request);

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

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

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

    final XmlPage rpPage = button.click();

    webClient.close();
    return rpPage.asXml();
}
 
Example 11
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 12
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 13
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 14
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();
}
 
Example 15
Source File: AbstractTests.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@Test
public void testEntityExpansionAttack() 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("/entity.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();
}
 
Example 16
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 17
Source File: AbstractTests.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@Test
public void testConcurrentRequests() throws Exception {

    String url1 = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
    String url2 = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/test.html";
    String user = "bob";
    String password = "bob";

    // 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 idpPage1 = webClient.getPage(url1);
    final HtmlPage idpPage2 = webClient.getPage(url2);
    webClient.getOptions().setJavaScriptEnabled(true);
    Assert.assertEquals("IDP SignIn Response Form", idpPage1.getTitleText());
    Assert.assertEquals("IDP SignIn Response Form", idpPage2.getTitleText());

    // Invoke back on the page1 RP
    final HtmlForm form = idpPage1.getFormByName(getLoginFormName());
    final HtmlSubmitInput button = form.getInputByName("_eventId_submit");
    final HtmlPage rpPage1 = button.click();
    Assert.assertTrue("WS Federation Systests Examples".equals(rpPage1.getTitleText())
                      || "WS Federation Systests Spring Examples".equals(rpPage1.getTitleText()));

    String bodyTextContent1 = rpPage1.getBody().getTextContent();

    Assert.assertTrue("Principal not " + user,
                      bodyTextContent1.contains("userPrincipal=" + user));

    // Invoke back on the page2 RP
    final HtmlForm form2 = idpPage2.getFormByName(getLoginFormName());
    final HtmlSubmitInput button2 = form2.getInputByName("_eventId_submit");
    final HtmlPage rpPage2 = button2.click();
    String bodyTextContent2 = rpPage2.getBody().getTextContent();

    Assert.assertTrue("Unexpected content of RP page", bodyTextContent2.contains("Secure Test"));

    webClient.close();
}
 
Example 18
Source File: AbstractTests.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@Test
public void testAliceModifiedSignature() 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"))) {
            // Now modify the Signature
            String value = result.getAttributeNS(null, "value");
            if (value.contains("alice")) {
                value = value.replace("alice", "bob");
            } else {
                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 signature");
    } catch (FailingHttpStatusCodeException ex) {
        // expected
        Assert.assertTrue(401 == ex.getStatusCode() || 403 == ex.getStatusCode());
    }

    webClient.close();
}
 
Example 19
Source File: FederationTest.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() + "/fedizhelloworldnoreqvalidation/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 20
Source File: TomcatTest.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();
}