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

The following examples show how to use com.gargoylesoftware.htmlunit.WebClient#close() . 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: PageFunctionTest.java    From tool.accelerate.core with Apache License 2.0 6 votes vote down vote up
@Test
public void headingTest() {
    final WebClient webClient = new WebClient();
    webClient.getOptions().setJavaScriptEnabled(false);
    HtmlPage page;
    String port = System.getProperty("liberty.test.port");
    try {
        page = webClient.getPage("http://localhost:" + port + "/start/");
        String title = page.getTitleText();
        assertTrue("Title is " + title, title.equals("Liberty app accelerator"));
    } catch (Exception e){
        org.junit.Assert.fail("Caught exception: " + e);
    } finally {
        webClient.close();
    }
}
 
Example 2
Source File: PageFunctionTest.java    From tool.accelerate.core with Apache License 2.0 6 votes vote down vote up
@Ignore
@Test
// TODO: This method of testing does not work for angular, need to find an alternative method of testing
public void techFormTest() {
    final WebClient webClient = new WebClient(BrowserVersion.CHROME);
    HtmlPage page;
    String port = System.getProperty("liberty.test.port");
    try {
        page = webClient.getPage("http://localhost:" + port + "/start/");
        DomElement techForm = page.getElementById("techTable");
        DomElement formBody = techForm.getFirstElementChild();
        int count = formBody.getChildElementCount();
        // We expect there to be more than one child element, otherwise the 
        // javascript has not created the tech table properly.
        assertTrue("Expected more than one element in the tech table, instead found " + count, count > 1);
    } catch (Exception e){
        org.junit.Assert.fail("Caught exception: " + e.getCause().toString());
    } finally {
        webClient.close();
    }
}
 
Example 3
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testUnsignedRequest() 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.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");

    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 4
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testBadWHR() throws Exception {
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
    url += "wa=wsignin1.0";
    url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A-xyz";
    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 whr value");
    } catch (FailingHttpStatusCodeException ex) {
        Assert.assertEquals(ex.getStatusCode(), 500);
    }

    webClient.close();
}
 
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 testEmptySeparateSignature() 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.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");

    String authnRequestEncoded = encodeAuthnRequest(authnRequest);

    String relayState = UUID.randomUUID().toString();

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

    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 6
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 7
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testBadIssuer() 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-xyz", 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 8
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testEntityExpansionWReq() throws Exception {
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
    url += "wa=wsignin1.0";
    url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
    url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
    String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
    url += "&wreply=" + wreply;

    String currentDir = new File(".").getCanonicalPath();
    File f = new File(currentDir + "/src/test/resources/entity_wreq.xml");
    String entity = new String(Files.readAllBytes(f.toPath()), "UTF-8");
    String validWreq =
        "<RequestSecurityToken xmlns=\"http://docs.oasis-open.org/ws-sx/ws-trust/200512\">"
        + "<TokenType>&m;http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0</TokenType>"
        + "</RequestSecurityToken>";

    url += "&wreq=" + URLEncoder.encode(entity + validWreq, "UTF-8");

    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 wreq value");
    } catch (FailingHttpStatusCodeException ex) {
        Assert.assertEquals(ex.getStatusCode(), 400);
    }

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

    String testWReq =
        "<RequestSecurityToken xmlns=\"http://docs.oasis-open.org/ws-sx/ws-trust/200512\">"
        + "<TokenType>http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV3.0</TokenType>"
        + "</RequestSecurityToken>";
    url += "&wreq=" + URLEncoder.encode(testWReq, "UTF-8");

    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 wreq value");
    } catch (FailingHttpStatusCodeException ex) {
        Assert.assertEquals(ex.getStatusCode(), 400);
    }

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

    if (!isWSFederation()) {
        return;
    }

    String url = "https://localhost:" + getRpHttpsPort()
        + "/" + getServletContextName() + "/FederationMetadata/2007-06/FederationMetadata.xml";

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

    final XmlPage rpPage = webClient.getPage(url);
    final String xmlContent = rpPage.asXml();
    Assert.assertTrue(xmlContent.startsWith("<md:EntityDescriptor"));

    // Now validate the Signature
    Document doc = rpPage.getXmlDocument();

    doc.getDocumentElement().setIdAttributeNS(null, "ID", true);

    Node signatureNode =
        DOMUtils.getChild(doc.getDocumentElement(), "Signature");
    Assert.assertNotNull(signatureNode);

    XMLSignature signature = new XMLSignature((Element)signatureNode, "");
    KeyInfo ki = signature.getKeyInfo();
    Assert.assertNotNull(ki);
    Assert.assertNotNull(ki.getX509Certificate());

    Assert.assertTrue(signature.checkSignatureValue(ki.getX509Certificate()));

    webClient.close();
}
 
Example 11
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testNoIssuer() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/"
        + getServletContextName() + "/secure/fedservlet";
    AuthnRequest authnRequest =
        new DefaultAuthnRequestBuilder().createAuthnRequest(
            null, null, 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 12
Source File: AbstractClientCertTests.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testClientAuthentication() throws Exception {
    String url = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";

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

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

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

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

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

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

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

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

    webClient.close();
}
 
Example 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
@org.junit.Test
public void testMaliciousRedirect() throws Exception {
    if (!isWSFederation()) {
        return;
    }

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

    CookieManager cookieManager = new CookieManager();

    // 1. Login
    HTTPTestUtils.loginWithCookieManager(url, user, password, getIdpHttpsPort(), getLoginFormName(), cookieManager);

    // 2. Now we should have a cookie from the RP and IdP and should be able to do
    // subsequent requests without authenticate again. Lets test this first.
    WebClient webClient = new WebClient();
    webClient.setCookieManager(cookieManager);
    webClient.getOptions().setUseInsecureSSL(true);
    HtmlPage rpPage = webClient.getPage(url);
    Assert.assertTrue("WS Federation Systests Examples".equals(rpPage.getTitleText())
                      || "WS Federation Systests Spring Examples".equals(rpPage.getTitleText()));

    // 3. Now a malicious user sends the client a URL with a bad "wreply" address to the IdP
    String maliciousURL = "https://www.apache.org/attack";
    String idpUrl
     = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation";
    idpUrl += "?wa=wsignin1.0&wreply=" + URLEncoder.encode(maliciousURL, "UTF-8");
    idpUrl += "&wtrealm=urn%3Aorg%3Aapache%3Acxf%3Afediz%3Afedizhelloworld";
    idpUrl += "&whr=urn%3Aorg%3Aapache%3Acxf%3Afediz%3Aidp%3Arealm-A";
    webClient.close();

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

    webClient2.getOptions().setJavaScriptEnabled(false);
    try {
        webClient2.getPage(idpUrl);
        Assert.fail("Failure expected on a bad wreply address");
    } catch (FailingHttpStatusCodeException ex) {
        Assert.assertEquals(ex.getStatusCode(), 400);
    }
    webClient2.close();
}
 
Example 15
Source File: KerberosTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testKerberos() throws Exception {
    String url = "https://localhost:" + getRpHttpsPort() + "/fedizhelloworld/secure/fedservlet";
    // Get a Kerberos Ticket +  Base64 encode it
    String ticket = getEncodedKerberosTicket(false);

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);

    webClient.getOptions().setJavaScriptEnabled(false);
    webClient.addRequestHeader("Authorization", "Negotiate " + ticket);
    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");

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

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

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

    webClient.close();
}
 
Example 16
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 17
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSuccessfulSSOInvokeOnIdP() 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.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.addRequestHeader("Authorization", "Basic "
        + Base64.getEncoder().encodeToString((USER + ":" + PWD).getBytes(UTF_8)));

    //
    // 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 - change the credentials to make sure the session is set up correctly
    //

    webClient.removeRequestHeader("Authorization");
    webClient.addRequestHeader("Authorization", "Basic "
        + Base64.getEncoder().encodeToString(("mallory" + ":" + PWD).getBytes(UTF_8)));

    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();
}
 
Example 18
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();
}
 
Example 19
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSeparateSignatureRSASHA256() 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.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");

    String authnRequestEncoded = encodeAuthnRequest(authnRequest);

    String urlEncodedRequest = URLEncoder.encode(authnRequestEncoded, UTF_8.name());

    String relayState = UUID.randomUUID().toString();

    // Sign request
    Crypto crypto = CryptoFactory.getInstance("stsKeystoreA.properties");

    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("realma");

    // Get the private key
    PrivateKey privateKey = crypto.getPrivateKey("realma", "realma");

    java.security.Signature signature = java.security.Signature.getInstance("SHA256withRSA");
    signature.initSign(privateKey);

    String encodedSignatureAlgorithm =
            URLEncoder.encode("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", UTF_8.name());
    String requestToSign = SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest
            + "&" + SSOConstants.RELAY_STATE + "=" + relayState
            + "&" + SSOConstants.SIG_ALG + "=" + encodedSignatureAlgorithm;

    signature.update(requestToSign.getBytes(UTF_8));
    byte[] signBytes = signature.sign();

    String encodedSignature = Base64.getEncoder().encodeToString(signBytes);

    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml/up?"
            + SSOConstants.RELAY_STATE + "=" + relayState
            + "&" + SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest
            + "&" + SSOConstants.SIG_ALG + "=" + encodedSignatureAlgorithm
            + "&" + SSOConstants.SIGNATURE + "=" + URLEncoder.encode(encodedSignature, 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);
    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));

    webClient.close();
}
 
Example 20
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();
}