Java Code Examples for com.gargoylesoftware.htmlunit.HttpMethod#POST

The following examples show how to use com.gargoylesoftware.htmlunit.HttpMethod#POST . 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: DoubleEquivalenceSubmissionTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void attack(int gameId, String mutant) throws FailingHttpStatusCodeException, IOException {
	WebRequest attackRequest = new WebRequest(new URL("http://localhost:8080" + Paths.BATTLEGROUND_GAME),
			HttpMethod.POST);
	// // Then we set the request parameters
	attackRequest.setRequestParameters(Arrays.asList(new NameValuePair[] {
			new NameValuePair("formType", "createMutant"), new NameValuePair("gameId", "" + gameId),
			// TODO Encoded somehow ?
			new NameValuePair("mutant", "" + mutant) }));
	// curl -X POST \
	// --data "formType=createMutant&gameId=${gameId}" \
	// --data-urlencode mutant@${mutant} \
	// --cookie "${cookie}" --cookie-jar "${cookie}" \
	// -w @curl-format.txt \
	// -s ${CODE_DEFENDER_URL}/multiplayergame
	browser.getPage(attackRequest);

}
 
Example 2
Source File: XMLHTTPRequest.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Prepares the WebRequest that will be sent.
 * @param content the content to send
 */
private void prepareRequest(final Object content) {
    if (content != null && content != Undefined.instance) {
        if (!"".equals(content) && HttpMethod.GET == webRequest_.getHttpMethod()) {
            webRequest_.setHttpMethod(HttpMethod.POST);
        }
        if (HttpMethod.POST == webRequest_.getHttpMethod()
                || HttpMethod.PUT == webRequest_.getHttpMethod()
                || HttpMethod.PATCH == webRequest_.getHttpMethod()) {
            if (content instanceof FormData) {
                ((FormData) content).fillRequest(webRequest_);
            }
            else {
                final String body = Context.toString(content);
                if (!body.isEmpty()) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Setting request body to: " + body);
                    }
                    webRequest_.setRequestBody(body);
                }
            }
        }
    }
}
 
Example 3
Source File: HtmlFormTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Test order of submitted parameters matches order of elements in form.
 * @throws Exception if the test fails
 */
@Test
public void submit_FormElementOrder() throws Exception {
    final String html
        = "<html><head></head><body><form method='post' action=''>\n"
        + "<input type='submit' name='dispatch' value='Save' id='submitButton'>\n"
        + "<input type='hidden' name='dispatch' value='TAB'>\n"
        + "</form></body></html>";
    final WebClient client = getWebClientWithMockWebConnection();

    final MockWebConnection webConnection = getMockWebConnection();
    webConnection.setDefaultResponse(html);

    final WebRequest request = new WebRequest(URL_FIRST, HttpMethod.POST);

    final HtmlPage page = client.getPage(request);
    final HtmlInput submitButton = page.getHtmlElementById("submitButton");
    submitButton.click();

    final List<NameValuePair> collectedParameters = webConnection.getLastParameters();
    final List<NameValuePair> expectedParameters = Arrays.asList(new NameValuePair[] {
        new NameValuePair("dispatch", "Save"),
        new NameValuePair("dispatch", "TAB"),
    });
    assertEquals(expectedParameters, collectedParameters);
}
 
Example 4
Source File: HtmlForm2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts(DEFAULT = "application/x-www-form-urlencoded",
        IE = "multipart/form-data")
public void inputTypeImageWithFormEnctype() throws Exception {
    final String html = "<!DOCTYPE html>\n"
        + "<html><head></head>\n"
        + "<body>\n"
        + "  <p>hello world</p>\n"
        + "  <form id='myForm' action='" + URL_SECOND
                            + "' method='" + HttpMethod.POST
                            + "' enctype='" + FormEncodingType.MULTIPART.getName() + "'>\n"
        + "    <input id='myButton' type='image' formenctype='" + FormEncodingType.URL_ENCODED.getName() + "' />\n"
        + "  </form>\n"
        + "</body></html>";
    final String secondContent = "second content";

    getMockWebConnection().setResponse(URL_SECOND, secondContent);

    final WebDriver driver = loadPage2(html, URL_FIRST);
    driver.findElement(By.id("myButton")).click();

    assertEquals(URL_SECOND.toString(), getMockWebConnection().getLastWebRequest().getUrl());
    assertEquals(getExpectedAlerts()[0],
                getMockWebConnection().getLastWebRequest().getEncodingType().getName());
}
 
Example 5
Source File: HtmlForm2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void buttonWithFormEnctype() throws Exception {
    final String html = "<!DOCTYPE html>\n"
        + "<html><head></head>\n"
        + "<body>\n"
        + "  <p>hello world</p>\n"
        + "  <form id='myForm' action='" + URL_SECOND
                            + "' method='" + HttpMethod.POST
                            + "' enctype='" + FormEncodingType.URL_ENCODED.getName() + "'>\n"
        + "    <input type='file' value='file1'>\n"
        + "    <button id='myButton' type='submit' formenctype='" + FormEncodingType.MULTIPART.getName()
        + "'>Submit with different form encoding type</button>\n"
        + "  </form>\n"
        + "</body></html>";
    final String secondContent = "second content";

    getMockWebConnection().setResponse(URL_SECOND, secondContent);

    final WebDriver driver = loadPage2(html);
    driver.findElement(By.id("myButton")).click();

    assertEquals(2, getMockWebConnection().getRequestCount());
    assertEquals(URL_SECOND.toString(), getMockWebConnection().getLastWebRequest().getUrl());
    assertEquals(FormEncodingType.MULTIPART, getMockWebConnection().getLastWebRequest().getEncodingType());
}
 
Example 6
Source File: HtmlForm2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void inputTypeSubmitWithFormMethod() throws Exception {
    final String html = "<!DOCTYPE html>\n"
        + "<html><head></head>\n"
        + "<body>\n"
        + "  <p>hello world</p>\n"
        + "  <form id='myForm' action='" + URL_SECOND
                            + "' method='" + HttpMethod.POST + "'>\n"
        + "    <input id='myButton' type='submit' formmethod='" + HttpMethod.GET + "' />\n"
        + "  </form>\n"
        + "</body></html>";
    final String secondContent = "second content";

    getMockWebConnection().setResponse(URL_SECOND, secondContent);

    final WebDriver driver = loadPage2(html);
    driver.findElement(By.id("myButton")).click();

    assertEquals(2, getMockWebConnection().getRequestCount());
    assertEquals(URL_SECOND.toString(), getMockWebConnection().getLastWebRequest().getUrl());
    assertEquals(HttpMethod.GET, getMockWebConnection().getLastWebRequest().getHttpMethod());
}
 
Example 7
Source File: HtmlForm2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void buttonSubmitWithFormMethod() throws Exception {
    final String html = "<!DOCTYPE html>\n"
        + "<html><head></head>\n"
        + "<body>\n"
        + "  <p>hello world</p>\n"
        + "  <form id='myForm' action='" + URL_SECOND
                            + "' method='" + HttpMethod.POST + "'>\n"
        + "    <button id='myButton' type='submit' formmethod='" + HttpMethod.GET
                    + "'>Submit with different form method</button>\n"
        + "  </form>\n"
        + "</body></html>";
    final String secondContent = "second content";

    getMockWebConnection().setResponse(URL_SECOND, secondContent);

    final WebDriver driver = loadPage2(html);
    driver.findElement(By.id("myButton")).click();

    assertEquals(2, getMockWebConnection().getRequestCount());
    assertEquals(URL_SECOND.toString(), getMockWebConnection().getLastWebRequest().getUrl());
    assertEquals(HttpMethod.GET, getMockWebConnection().getLastWebRequest().getHttpMethod());
}
 
Example 8
Source File: HelperUser.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void attack(int gameId, String mutant) throws FailingHttpStatusCodeException, IOException {
	WebRequest attackRequest = new WebRequest(new URL(codedefendersHome + Paths.BATTLEGROUND_GAME), HttpMethod.POST);
	// // Then we set the request parameters
	attackRequest.setRequestParameters(Arrays.asList(new NameValuePair[] {
			new NameValuePair("formType", "createMutant"), new NameValuePair("gameId", "" + gameId),
			// TODO Encoded somehow ?
			new NameValuePair("mutant", "" + mutant) }));
	// curl -X POST \
	// --data "formType=createMutant&gameId=${gameId}" \
	// --data-urlencode mutant@${mutant} \
	// --cookie "${cookie}" --cookie-jar "${cookie}" \
	// -w @curl-format.txt \
	// -s ${CODE_DEFENDER_URL}/multiplayergame
	browser.getPage(attackRequest);

}
 
Example 9
Source File: HtmlForm2Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
public void formMultipartEncodingTypeTest() throws Exception {
    final String html = "<!DOCTYPE html>\n"
        + "<html><head></head>\n"
        + "<body>\n"
        + "  <p>hello world</p>\n"
        + "  <form id='myForm' action='" + URL_SECOND
                + "' method='" + HttpMethod.POST
                + "' enctype='" + FormEncodingType.MULTIPART.getName()
                + "'>\n"
        + "    <input type='file' value='file1'>\n"
        + "    <button id='myButton' type='submit'>Submit</button>\n"
        + "  </form>\n"
        + "</body></html>";
    final String secondContent
        = "<html><head><title>second</title></head><body>\n"
        + "  <p>hello world</p>\n"
        + "</body></html>";

    getMockWebConnection().setResponse(URL_SECOND, secondContent);

    final WebDriver driver = loadPage2(html, URL_FIRST);
    driver.findElement(By.id("myButton")).click();

    assertEquals(2, getMockWebConnection().getRequestCount());
    assertEquals(URL_SECOND.toString(), getMockWebConnection().getLastWebRequest().getUrl());
    assertEquals(FormEncodingType.MULTIPART, getMockWebConnection().getLastWebRequest().getEncodingType());
}
 
Example 10
Source File: HelperUser.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void doLogin() throws FailingHttpStatusCodeException, IOException {
	WebRequest loginRequest = new WebRequest(new URL(codedefendersHome + Paths.LOGIN), HttpMethod.POST);
	// // Then we set the request parameters
	loginRequest.setRequestParameters(Arrays.asList(
			new NameValuePair("formType", "login"),
			new NameValuePair("username", user.getUsername()),
			new NameValuePair("password", password)));
	// Finally, we can get the page
	HtmlPage retunToGamePage = browser.getPage(loginRequest);
}
 
Example 11
Source File: DoubleEquivalenceSubmissionTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void doLogin() throws FailingHttpStatusCodeException, IOException {
	WebRequest loginRequest = new WebRequest(new URL("http://localhost:8080"+ Paths.LOGIN), HttpMethod.POST);
	// // Then we set the request parameters
	loginRequest.setRequestParameters(Arrays.asList(new NameValuePair[] {
			new NameValuePair("formType", "login"), new NameValuePair("username", user.getUsername()),
			new NameValuePair("password", password), }));
	// Finally, we can get the page
	HtmlPage retunToGamePage = browser.getPage(loginRequest);
}
 
Example 12
Source File: HelperUser.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
public HtmlPage doRegister() throws FailingHttpStatusCodeException, IOException {
	WebRequest registerRequest = new WebRequest(new URL(codedefendersHome + Paths.LOGIN), HttpMethod.POST);
	registerRequest.setRequestParameters(Arrays.asList(
			new NameValuePair("formType", "create"),
			new NameValuePair("username", user.getUsername()),
			new NameValuePair("email", user.getEmail()),
			new NameValuePair("password", password),
			new NameValuePair("confirm", password)));
	return browser.getPage(registerRequest);

}
 
Example 13
Source File: DrawPage.java    From keycloak-dropwizard-integration with Apache License 2.0 5 votes vote down vote up
public static LoginPage<DrawPage> openWithoutLogin(WebClient webClient, URL url, LocalDate parse)
        throws IOException {
    WebRequest request = new WebRequest(new URL(url.toString() + "/draw"), HttpMethod.POST);
    List<NameValuePair> parameters = new ArrayList<>();
    parameters.add(new NameValuePair("date", "2015-01-01"));
    request.setRequestParameters(parameters);
    return new LoginPage<>(webClient.getPage(request), DrawPage.class);
}
 
Example 14
Source File: AbstractOIDCTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testOIDCLoginForPublicClientWithRefreshTokenScope() throws Exception {
    final UriBuilder authorizationUrl = oidcEndpointBuilder("/idp/authorize")
        .queryParam("client_id", publicClientId)
        .queryParam("response_type", "code")
        .queryParam("scope", "openid refreshToken")
        .queryParam("redirect_uri", REDIRECT_URL);

    // Login to the OIDC authorization endpoint + get the authorization code
    final String authorizationCode;
    try (WebClient webClient = setupWebClientIDP("alice", "ecila")) {
        final HtmlPage confirmationPage = login(authorizationUrl, webClient);
        final HtmlForm form = confirmationPage.getForms().get(0);
        authorizationCode = form.getButtonByName("oauthDecision").click().getWebResponse().getContentAsString();
    }

    // Now use the code to get an IdToken
    Map<String, Object> json = getTokenJson(authorizationCode, publicClientId, null);

    // Get the access token
    final String accessToken = json.get("access_token").toString();

    // Refresh access token
    try (WebClient webClient = setupWebClient()) {
        WebRequest request = new WebRequest(oidcEndpoint("/oauth2/token"), HttpMethod.POST);

        request.setRequestParameters(Arrays.asList(
            new NameValuePair("client_id", publicClientId),
            new NameValuePair("grant_type", "refresh_token"),
            new NameValuePair("refresh_token", json.get("refresh_token").toString())));

        json = new JsonMapObjectReaderWriter().fromJson(
            webClient.getPage(request).getWebResponse().getContentAsString());
        assertNotEquals(accessToken, json.get("access_token").toString());
    }
}
 
Example 15
Source File: DoubleEquivalenceSubmissionTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void startGame(int gameID) throws FailingHttpStatusCodeException, IOException {

			WebRequest startGameRequest = new WebRequest(new URL("http://localhost:8080" + Paths.BATTLEGROUND_GAME),
					HttpMethod.POST);
			// // Then we set the request parameters
			startGameRequest.setRequestParameters(Arrays.asList(new NameValuePair[] {
					new NameValuePair("formType", "startGame"), new NameValuePair("gameId", "" + gameID) }));
			// Finally, we can get the page
			// Not sure why this returns TextPage and not HtmlPage
			browser.getPage(startGameRequest);

		}
 
Example 16
Source File: HelperUser.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
public HtmlPage startGame(int gameID) throws FailingHttpStatusCodeException, IOException {

		WebRequest startGameRequest = new WebRequest(new URL(codedefendersHome + Paths.BATTLEGROUND_GAME), HttpMethod.POST);
		// // Then we set the request parameters
		startGameRequest.setRequestParameters(Arrays.asList(new NameValuePair[] {
				new NameValuePair("formType", "startGame"), new NameValuePair("gameId", "" + gameID) }));
		// Finally, we can get the page
		return browser.getPage(startGameRequest);

	}
 
Example 17
Source File: AbstractOIDCTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testAccessTokenRevocationWrongClient() throws Exception {
    final UriBuilder authorizationUrl = oidcEndpointBuilder("/idp/authorize")
        .queryParam("client_id", confidentialClientId)
        .queryParam("response_type", "code")
        .queryParam("scope", "openid");

    // Login to the OIDC token endpoint + get the authorization code
    final String authorizationCode = loginAndGetAuthorizationCode(authorizationUrl, "alice", "ecila");

    // Now use the code to get an IdToken
    final Map<String, Object> json =
        getTokenJson(authorizationCode, confidentialClientId, confidentialClientSecret);

    // Check the IdToken
    validateIdToken(getIdToken(json), confidentialClientId);

    // Get the access token
    final String accessToken = json.get("access_token").toString();

    // Introspect the token and check it's valid
    WebRequest introspectionRequest = new WebRequest(oidcEndpoint("/oauth2/introspect"), HttpMethod.POST);
    introspectionRequest.setRequestParameters(Arrays.asList(
        new NameValuePair("token", accessToken)));

    try (WebClient webClient = setupWebClientRP(confidentialClientId, confidentialClientSecret)) {
        String introspectionResponse =
            webClient.getPage(introspectionRequest).getWebResponse().getContentAsString();

        assertTrue(introspectionResponse.contains("\"active\":true"));

        try (WebClient webClient2 = setupWebClientIDP("alice", "ecila")) {
            final UriBuilder clientsUrl = oidcEndpointBuilder("/console/clients/{path}");
            final HtmlPage registerPage = login(clientsUrl.resolveTemplate("path", "register"), webClient2);

            HtmlPage registeredClientsPage = registerConfidentialClient(registerPage, "client3",
                "https://localhost:12345", "https://cxf.apache.org", "https://localhost:12345");

            final String clientId = getClientIdByName("client3", registeredClientsPage);
            final HtmlPage registeredClientPage = webClient2
                .getPage(clientsUrl.resolveTemplate("path", clientId).build().toURL());
            final String clientSecret = getClientSecret(registeredClientPage, clientId);

            // Now try to revoke the token as the other client
            try (WebClient webClient3 = setupWebClientRP(clientId, clientSecret)) {
                WebRequest revocationRequest = new WebRequest(oidcEndpoint("/oauth2/revoke"), HttpMethod.POST);
                revocationRequest.setRequestParameters(Arrays.asList(
                    new NameValuePair("token", accessToken)));

                webClient3.getPage(revocationRequest);
            } finally {
                deleteClient(registeredClientPage);
            }
        }

        // Now introspect the token again and check it's still valid
        introspectionResponse = webClient.getPage(introspectionRequest).getWebResponse().getContentAsString();

        assertTrue(introspectionResponse.contains("\"active\":true"));
    }
}
 
Example 18
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSuccessfulInvokeOnIdPUsingPOST() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML AuthnRequest
    Document doc = DOMUtils.createDocument();
    doc.appendChild(doc.createElement("root"));
    // Create the 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/up");
    signAuthnRequest(authnRequest);

    Element authnRequestElement = OpenSAMLUtil.toDom(authnRequest, doc);

    // Don't inflate the token...
    String requestMessage = DOM2Writer.nodeToString(authnRequestElement);
    String authnRequestEncoded = Base64Utility.encode(requestMessage.getBytes(UTF_8.name()));

    String relayState = UUID.randomUUID().toString();
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml/up";

    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);

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

    request.setRequestParameters(new ArrayList<NameValuePair>());
    request.getRequestParameters().add(new NameValuePair(SSOConstants.RELAY_STATE, relayState));
    request.getRequestParameters().add(new NameValuePair(SSOConstants.SAML_REQUEST, authnRequestEncoded));

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

    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 19
Source File: HtmlForm.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
/**
 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
 *
 * Gets the request for a submission of this form with the specified SubmittableElement.
 * @param submitElement the element that caused the submit to occur
 * @return the request
 */
public WebRequest getWebRequest(final SubmittableElement submitElement) {
    final HtmlPage htmlPage = (HtmlPage) getPage();
    final List<NameValuePair> parameters = getParameterListForSubmit(submitElement);
    final HttpMethod method;
    final String methodAttribute = getMethodAttribute();
    if ("post".equalsIgnoreCase(methodAttribute)) {
        method = HttpMethod.POST;
    }
    else {
        if (!"get".equalsIgnoreCase(methodAttribute) && StringUtils.isNotBlank(methodAttribute)) {
            notifyIncorrectness("Incorrect submit method >" + getMethodAttribute() + "<. Using >GET<.");
        }
        method = HttpMethod.GET;
    }

    final BrowserVersion browser = getPage().getWebClient().getBrowserVersion();
    String actionUrl = getActionAttribute();
    String anchor = null;
    String queryFromFields = "";
    if (HttpMethod.GET == method) {
        if (actionUrl.contains("#")) {
            anchor = StringUtils.substringAfter(actionUrl, "#");
        }
        final Charset enc = getPage().getCharset();
        queryFromFields =
            URLEncodedUtils.format(Arrays.asList(NameValuePair.toHttpClient(parameters)), enc);

        // action may already contain some query parameters: they have to be removed
        actionUrl = StringUtils.substringBefore(actionUrl, "#");
        actionUrl = StringUtils.substringBefore(actionUrl, "?");
        parameters.clear(); // parameters have been added to query
    }
    URL url;
    try {
        if (actionUrl.isEmpty()) {
            url = WebClient.expandUrl(htmlPage.getUrl(), actionUrl);
        }
        else {
            url = htmlPage.getFullyQualifiedUrl(actionUrl);
        }

        if (!queryFromFields.isEmpty()) {
            url = UrlUtils.getUrlWithNewQuery(url, queryFromFields);
        }

        if (HttpMethod.GET == method && browser.hasFeature(FORM_SUBMISSION_URL_WITHOUT_HASH)
                && WebClient.URL_ABOUT_BLANK != url) {
            url = UrlUtils.getUrlWithNewRef(url, null);
        }
        else if (HttpMethod.POST == method
                && browser.hasFeature(FORM_SUBMISSION_URL_WITHOUT_HASH)
                && WebClient.URL_ABOUT_BLANK != url
                && StringUtils.isEmpty(actionUrl)) {
            url = UrlUtils.getUrlWithNewRef(url, null);
        }
        else if (anchor != null
                && WebClient.URL_ABOUT_BLANK != url) {
            url = UrlUtils.getUrlWithNewRef(url, anchor);
        }
    }
    catch (final MalformedURLException e) {
        throw new IllegalArgumentException("Not a valid url: " + actionUrl);
    }

    final WebRequest request = new WebRequest(url, method);
    request.setAdditionalHeader(HttpHeader.ACCEPT, browser.getHtmlAcceptHeader());
    request.setAdditionalHeader(HttpHeader.ACCEPT_ENCODING, "gzip, deflate");
    request.setRequestParameters(parameters);
    if (HttpMethod.POST == method) {
        request.setEncodingType(FormEncodingType.getInstance(getEnctypeAttribute()));
    }
    request.setCharset(getSubmitCharset());

    String referer = htmlPage.getUrl().toExternalForm();
    request.setAdditionalHeader(HttpHeader.REFERER, referer);

    if (HttpMethod.POST == method
            && browser.hasFeature(FORM_SUBMISSION_HEADER_ORIGIN)) {
        referer = StringUtils.stripEnd(referer, "/");
        request.setAdditionalHeader(HttpHeader.ORIGIN, referer);
    }
    if (HttpMethod.POST == method
            && browser.hasFeature(FORM_SUBMISSION_HEADER_CACHE_CONTROL_MAX_AGE)) {
        request.setAdditionalHeader(HttpHeader.CACHE_CONTROL, "max-age=0");
    }
    if (browser.hasFeature(FORM_SUBMISSION_HEADER_CACHE_CONTROL_NO_CACHE)) {
        request.setAdditionalHeader(HttpHeader.CACHE_CONTROL, "no-cache");
    }

    return request;
}
 
Example 20
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();
}