Java Code Examples for com.gargoylesoftware.htmlunit.WebRequest#setRequestParameters()

The following examples show how to use com.gargoylesoftware.htmlunit.WebRequest#setRequestParameters() . 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: AbstractOIDCTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testCSRFClientRegistration() throws Exception {
    // Login to the client page successfully
    try (WebClient webClient = setupWebClientIDP("alice", "ecila")) {
        final UriBuilder clientsUrl = oidcEndpointBuilder("/console/clients");
        login(clientsUrl, webClient);

        // Register a new client
        WebRequest request = new WebRequest(clientsUrl.build().toURL(), HttpMethod.POST);
        request.setRequestParameters(Arrays.asList(
            new NameValuePair("client_name", "bad_client"),
            new NameValuePair("client_type", "confidential"),
            new NameValuePair("client_redirectURI", "https://127.0.0.1"),
            new NameValuePair("client_audience", ""),
            new NameValuePair("client_logoutURI", ""),
            new NameValuePair("client_homeRealm", ""),
            new NameValuePair("client_csrfToken", "12345")));

        HtmlPage registeredClientPage = webClient.getPage(request);
        assertTrue(registeredClientPage.asXml().contains("Invalid CSRF Token"));
    }
}
 
Example 3
Source File: RoundTripAbstractTest.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
private void applyConfigViaWebUI(String jenkinsConfig) throws Exception {
    // The UI requires the path to the config file
    File f = tempFolder.newFile();
    writeToFile(jenkinsConfig, f.getAbsolutePath());

    // Call the replace url
    JenkinsRule.WebClient client = r.j.createWebClient();
    WebRequest request = new WebRequest(client.createCrumbedUrl("configuration-as-code/replace"), POST);
    NameValuePair param = new NameValuePair("_.newSource", f.toURI().toURL().toExternalForm());
    request.setRequestParameters(Collections.singletonList(param));
    request.setRequestParameters(Collections.singletonList(param));
    WebResponse response = client.loadWebResponse(request);
    assertEquals("Failed to POST to " + request.getUrl().toString(), 200, response.getStatusCode());
    String res = response.getContentAsString();
    /* The result page has:
    Configuration loaded from :
                    <ul>
                        <li>path</li>
                    </ul>
    path is the file used to store the configuration.
     */
    assertThat(res, containsString(f.toURI().toURL().toExternalForm()));
}
 
Example 4
Source File: DockerDirectiveGeneratorTest.java    From docker-workflow-plugin with MIT License 6 votes vote down vote up
private void assertGenerateDirective(@Nonnull AbstractDirective desc, @Nonnull String responseText) throws Exception {
    // First, make sure the expected response text actually matches the toGroovy for the directive.
    assertEquals(desc.toGroovy(true), responseText);

    // Then submit the form with the appropriate JSON (we generate it from the directive, but it matches the form JSON exactly)
    JenkinsRule.WebClient wc = r.createWebClient();
    WebRequest wrs = new WebRequest(new URL(r.getURL(), DirectiveGenerator.GENERATE_URL), HttpMethod.POST);
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("json", staplerJsonForDescr(desc).toString()));
    // WebClient.addCrumb *replaces* rather than *adds*:
    params.add(new NameValuePair(r.jenkins.getCrumbIssuer().getDescriptor().getCrumbRequestField(), r.jenkins.getCrumbIssuer().getCrumb(null)));
    wrs.setRequestParameters(params);
    WebResponse response = wc.getPage(wrs).getWebResponse();
    assertEquals("text/plain", response.getContentType());
    assertEquals(responseText, response.getContentAsString().trim());
}
 
Example 5
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 6
Source File: DoubleEquivalenceSubmissionTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void defend(int gameId, String test) throws FailingHttpStatusCodeException, IOException {
	WebRequest defendRequest = new WebRequest(new URL("http://localhost:8080" + Paths.BATTLEGROUND_GAME),
			HttpMethod.POST);
	// curl -X POST \
	// --data "formType=createTest&gameId=${gameId}" \
	// --data-urlencode test@${test} \
	// --cookie "${cookie}" --cookie-jar "${cookie}" \
	// -w @curl-format.txt \
	// -s ${CODE_DEFENDER_URL}/multiplayergame
	defendRequest.setRequestParameters(Arrays.asList(new NameValuePair[] {
			new NameValuePair("formType", "createTest"), new NameValuePair("gameId", "" + gameId),
			// TODO Encoded somehow ?
			new NameValuePair("test", "" + test) }));
	browser.getPage(defendRequest);
}
 
Example 7
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 8
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 9
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
/**
 * Adds a security crumb to the request.
 * Use {@link #createCrumbedUrl} instead if you intend to call {@link WebRequest#setRequestBody}, typical of a POST request.
 */
public WebRequest addCrumb(WebRequest req) {
    ArrayList<NameValuePair> params = new ArrayList<>();
    params.add(getCrumbHeaderNVP());
    List<NameValuePair> oldParams = req.getRequestParameters();
    if (oldParams != null) {
        params.addAll(oldParams);
    }
    req.setRequestParameters(params);
    return req;
}
 
Example 10
Source File: HelperUser.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void defend(int gameId, String test) throws FailingHttpStatusCodeException, IOException {
	WebRequest defendRequest = new WebRequest(new URL(codedefendersHome + Paths.BATTLEGROUND_GAME), HttpMethod.POST);
	// curl -X POST \
	// --data "formType=createTest&gameId=${gameId}" \
	// --data-urlencode test@${test} \
	// --cookie "${cookie}" --cookie-jar "${cookie}" \
	// -w @curl-format.txt \
	// -s ${CODE_DEFENDER_URL}/multiplayergame
	defendRequest.setRequestParameters(Arrays.asList(new NameValuePair[] {
			new NameValuePair("formType", "createTest"), new NameValuePair("gameId", "" + gameId),
			// TODO Encoded somehow ?
			new NameValuePair("test", "" + test) }));
	browser.getPage(defendRequest);
}
 
Example 11
Source File: URLSearchParams.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the specified request with the parameters in this {@code FormData}.
 * @param webRequest the web request to fill
 */
public void fillRequest(final WebRequest webRequest) {
    webRequest.setRequestBody(null);
    webRequest.setEncodingType(FormEncodingType.URL_ENCODED);

    if (params_.size() > 0) {
        final List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (Entry<String, String> entry : params_) {
            params.add(new NameValuePair(entry.getKey(), entry.getValue()));
        }
        webRequest.setRequestParameters(params);
    }
}
 
Example 12
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 13
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 14
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 15
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 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: AbstractOIDCTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testAccessTokenRevocation() 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
    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"));

        // Now revoke the token
        WebRequest revocationRequest = new WebRequest(oidcEndpoint("/oauth2/revoke"), HttpMethod.POST);
        revocationRequest.setRequestParameters(Arrays.asList(
            new NameValuePair("token", accessToken)));

        webClient.getPage(revocationRequest);

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

        assertTrue(introspectionResponse.contains("\"active\":false"));
    }
}
 
Example 18
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 19
Source File: FormData.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Sets the specified request with the parameters in this {@code FormData}.
 * @param webRequest the web request to fill
 */
public void fillRequest(final WebRequest webRequest) {
    webRequest.setEncodingType(FormEncodingType.MULTIPART);
    webRequest.setRequestParameters(requestParameters_);
}
 
Example 20
Source File: FormData.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * Sets the specified request with the parameters in this {@code FormData}.
 * @param webRequest the web request to fill
 */
public void fillRequest(final WebRequest webRequest) {
    webRequest.setEncodingType(FormEncodingType.MULTIPART);
    webRequest.setRequestParameters(requestParameters_);
}