Search in sources :

Example 31 with Page

use of com.gargoylesoftware.htmlunit.Page in project blueocean-plugin by jenkinsci.

the class JwtImplTest method getToken.

@Test
public void getToken() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    User user = j.jenkins.getUser("alice");
    user.setFullName("Alice Cooper");
    user.addProperty(new Mailer.UserProperty("alice@jenkins-ci.org"));
    JenkinsRule.WebClient webClient = j.createWebClient();
    webClient.login("alice");
    Page page = webClient.goTo("jwt-auth/token/", null);
    String token = page.getWebResponse().getResponseHeaderValue("X-BLUEOCEAN-JWT");
    Assert.assertNotNull(token);
    JsonWebStructure jsonWebStructure = JsonWebStructure.fromCompactSerialization(token);
    Assert.assertTrue(jsonWebStructure instanceof JsonWebSignature);
    JsonWebSignature jsw = (JsonWebSignature) jsonWebStructure;
    System.out.println(token);
    System.out.println(jsw.toString());
    String kid = jsw.getHeader("kid");
    Assert.assertNotNull(kid);
    page = webClient.goTo("jwt-auth/jwks/" + kid + "/", "application/json");
    //        for(NameValuePair valuePair: page.getWebResponse().getResponseHeaders()){
    //            System.out.println(valuePair);
    //        }
    JSONObject jsonObject = JSONObject.fromObject(page.getWebResponse().getContentAsString());
    System.out.println(jsonObject.toString());
    RsaJsonWebKey rsaJsonWebKey = new RsaJsonWebKey(jsonObject, null);
    JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds(// allow some leeway in validating time based claims to account for clock skew
    30).setRequireSubject().setVerificationKey(// verify the sign with the public key
    rsaJsonWebKey.getKey()).build();
    JwtClaims claims = jwtConsumer.processToClaims(token);
    Assert.assertEquals("alice", claims.getSubject());
    Map<String, Object> claimMap = claims.getClaimsMap();
    Map<String, Object> context = (Map<String, Object>) claimMap.get("context");
    Map<String, String> userContext = (Map<String, String>) context.get("user");
    Assert.assertEquals("alice", userContext.get("id"));
    Assert.assertEquals("Alice Cooper", userContext.get("fullName"));
    Assert.assertEquals("alice@jenkins-ci.org", userContext.get("email"));
}
Also used : User(hudson.model.User) JwtClaims(org.jose4j.jwt.JwtClaims) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) Mailer(hudson.tasks.Mailer) Page(com.gargoylesoftware.htmlunit.Page) JenkinsRule(org.jvnet.hudson.test.JenkinsRule) JsonWebSignature(org.jose4j.jws.JsonWebSignature) JSONObject(net.sf.json.JSONObject) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) JSONObject(net.sf.json.JSONObject) RsaJsonWebKey(org.jose4j.jwk.RsaJsonWebKey) Map(java.util.Map) JsonWebStructure(org.jose4j.jwx.JsonWebStructure) Test(org.junit.Test)

Example 32 with Page

use of com.gargoylesoftware.htmlunit.Page in project spring-framework by spring-projects.

the class MockMvcWebConnectionTests method contextPathEmpty.

@Test
public void contextPathEmpty() throws IOException {
    this.webClient.setWebConnection(new MockMvcWebConnection(this.mockMvc, this.webClient, ""));
    Page page = this.webClient.getPage("http://localhost/context/a");
    assertThat(page.getWebResponse().getStatusCode(), equalTo(200));
}
Also used : Page(com.gargoylesoftware.htmlunit.Page) Test(org.junit.Test)

Example 33 with Page

use of com.gargoylesoftware.htmlunit.Page in project camel by apache.

the class BoxConnectionHelper method createStandardAuthenticatedConnection.

public static BoxAPIConnection createStandardAuthenticatedConnection(BoxConfiguration configuration) {
    // Create web client for first leg of OAuth2
    //
    final WebClient webClient = new WebClient();
    final WebClientOptions options = webClient.getOptions();
    options.setRedirectEnabled(true);
    options.setJavaScriptEnabled(false);
    options.setThrowExceptionOnFailingStatusCode(true);
    options.setThrowExceptionOnScriptError(true);
    options.setPrintContentOnFailingStatusCode(LOG.isDebugEnabled());
    try {
        // use default SSP to create supported non-SSL protocols list
        final SSLContext sslContext = new SSLContextParameters().createSSLContext(null);
        options.setSSLClientProtocols(sslContext.createSSLEngine().getEnabledProtocols());
    } catch (GeneralSecurityException e) {
        throw ObjectHelper.wrapRuntimeCamelException(e);
    } catch (IOException e) {
        throw ObjectHelper.wrapRuntimeCamelException(e);
    } finally {
        if (webClient != null) {
            webClient.close();
        }
    }
    // disable default gzip compression, as htmlunit does not negotiate
    // pages sent with no compression
    new WebConnectionWrapper(webClient) {

        @Override
        public WebResponse getResponse(WebRequest request) throws IOException {
            request.setAdditionalHeader(HttpHeaders.ACCEPT_ENCODING, "identity");
            return super.getResponse(request);
        }
    };
    // add HTTP proxy if set
    final Map<String, Object> httpParams = configuration.getHttpParams();
    if (httpParams != null && httpParams.get("http.route.default-proxy") != null) {
        final HttpHost proxyHost = (HttpHost) httpParams.get("http.route.default-proxy");
        final Boolean socksProxy = (Boolean) httpParams.get("http.route.socks-proxy");
        final ProxyConfig proxyConfig = new ProxyConfig(proxyHost.getHostName(), proxyHost.getPort(), socksProxy != null ? socksProxy : false);
        options.setProxyConfig(proxyConfig);
    }
    // authorize application on user's behalf
    try {
        // generate anti-forgery token to prevent/detect CSRF attack
        final String csrfToken = String.valueOf(new SecureRandom().nextLong());
        final HtmlPage authPage = webClient.getPage(authorizationUrl(configuration.getClientId(), csrfToken));
        // look for <div role="error_message">
        final HtmlDivision div = authPage.getFirstByXPath("//div[contains(concat(' ', @class, ' '), ' error_message ')]");
        if (div != null) {
            final String errorMessage = div.getTextContent().replaceAll("\\s+", " ").replaceAll(" Show Error Details", ":").trim();
            throw new IllegalArgumentException("Error authorizing application: " + errorMessage);
        }
        // submit login credentials
        final HtmlForm loginForm = authPage.getFormByName("login_form");
        final HtmlTextInput login = loginForm.getInputByName("login");
        login.setText(configuration.getUserName());
        final HtmlPasswordInput password = loginForm.getInputByName("password");
        password.setText(configuration.getUserPassword());
        final HtmlSubmitInput submitInput = loginForm.getInputByName("login_submit");
        // submit consent
        final HtmlPage consentPage = submitInput.click();
        final HtmlForm consentForm = consentPage.getFormByName("consent_form");
        final HtmlButton consentAccept = consentForm.getButtonByName("consent_accept");
        // disable redirect to avoid loading redirect URL
        webClient.getOptions().setRedirectEnabled(false);
        // validate CSRF and get authorization code
        String redirectQuery;
        try {
            final Page redirectPage = consentAccept.click();
            redirectQuery = redirectPage.getUrl().getQuery();
        } catch (FailingHttpStatusCodeException e) {
            // escalate non redirect errors
            if (e.getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) {
                throw e;
            }
            final String location = e.getResponse().getResponseHeaderValue("Location");
            redirectQuery = new URL(location).getQuery();
        }
        final Map<String, String> params = new HashMap<String, String>();
        final Matcher matcher = QUERY_PARAM_PATTERN.matcher(redirectQuery);
        while (matcher.find()) {
            params.put(matcher.group(1), matcher.group(2));
        }
        final String state = params.get("state");
        if (!csrfToken.equals(state)) {
            throw new SecurityException("Invalid CSRF code!");
        } else {
            // get authorization code
            final String authorizationCode = params.get("code");
            return new BoxAPIConnection(configuration.getClientId(), configuration.getClientSecret(), authorizationCode);
        }
    } catch (BoxAPIException e) {
        throw new RuntimeCamelException(String.format("Box API connection failed: API returned the error code %d\n\n%s", e.getResponseCode(), e.getResponse()), e);
    } catch (Exception e) {
        throw new RuntimeCamelException(String.format("Box API connection failed: %s", e.getMessage()), e);
    }
}
Also used : WebClientOptions(com.gargoylesoftware.htmlunit.WebClientOptions) HtmlTextInput(com.gargoylesoftware.htmlunit.html.HtmlTextInput) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) HtmlPasswordInput(com.gargoylesoftware.htmlunit.html.HtmlPasswordInput) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) Page(com.gargoylesoftware.htmlunit.Page) HtmlDivision(com.gargoylesoftware.htmlunit.html.HtmlDivision) BoxAPIException(com.box.sdk.BoxAPIException) URL(java.net.URL) WebRequest(com.gargoylesoftware.htmlunit.WebRequest) HtmlForm(com.gargoylesoftware.htmlunit.html.HtmlForm) HtmlSubmitInput(com.gargoylesoftware.htmlunit.html.HtmlSubmitInput) HttpHost(org.apache.http.HttpHost) FailingHttpStatusCodeException(com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException) GeneralSecurityException(java.security.GeneralSecurityException) BoxAPIConnection(com.box.sdk.BoxAPIConnection) SecureRandom(java.security.SecureRandom) GeneralSecurityException(java.security.GeneralSecurityException) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) ProxyConfig(com.gargoylesoftware.htmlunit.ProxyConfig) WebClient(com.gargoylesoftware.htmlunit.WebClient) BoxAPIException(com.box.sdk.BoxAPIException) GeneralSecurityException(java.security.GeneralSecurityException) FailingHttpStatusCodeException(com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException) RuntimeCamelException(org.apache.camel.RuntimeCamelException) IOException(java.io.IOException) SSLContextParameters(org.apache.camel.util.jsse.SSLContextParameters) HtmlButton(com.gargoylesoftware.htmlunit.html.HtmlButton) RuntimeCamelException(org.apache.camel.RuntimeCamelException) WebConnectionWrapper(com.gargoylesoftware.htmlunit.util.WebConnectionWrapper)

Example 34 with Page

use of com.gargoylesoftware.htmlunit.Page in project sling by apache.

the class ITWebConsoleRemote method tailerHeader.

@Test
public void tailerHeader() throws Exception {
    Page page = webClient.getPage(prepareUrl("slinglog/tailer.txt?name=webconsoletest1.log"));
    String nosniffHeader = page.getWebResponse().getResponseHeaderValue("X-Content-Type-Options");
    assertEquals("nosniff", nosniffHeader);
}
Also used : TextPage(com.gargoylesoftware.htmlunit.TextPage) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) Page(com.gargoylesoftware.htmlunit.Page) Matchers.containsString(org.hamcrest.Matchers.containsString) Test(org.junit.Test)

Example 35 with Page

use of com.gargoylesoftware.htmlunit.Page in project core by weld.

the class WeldSeBuilderTest method test.

private void test(ServletContextHandler context) throws Exception {
    Server server = new Server(8080);
    context.setContextPath("/");
    server.setHandler(context);
    context.addServlet(TestServlet.class, "/test");
    server.start();
    try {
        WebClient webClient = new WebClient();
        webClient.setThrowExceptionOnFailingStatusCode(true);
        Page page = webClient.getPage("http://localhost:8080/test");
        assertEquals("Kitty", page.getWebResponse().getContentAsString().trim());
    } finally {
        // no need to stop Weld here, it is stopped by weld-servlet
        server.stop();
    }
}
Also used : Server(org.eclipse.jetty.server.Server) Page(com.gargoylesoftware.htmlunit.Page) WebClient(com.gargoylesoftware.htmlunit.WebClient)

Aggregations

Page (com.gargoylesoftware.htmlunit.Page)62 Test (org.junit.Test)39 WebClient (com.gargoylesoftware.htmlunit.WebClient)33 HtmlPage (com.gargoylesoftware.htmlunit.html.HtmlPage)15 PublicAtsApi (com.axway.ats.common.PublicAtsApi)9 HtmlForm (com.gargoylesoftware.htmlunit.html.HtmlForm)5 File (java.io.File)5 IOException (java.io.IOException)5 URL (java.net.URL)5 JenkinsRule (org.jvnet.hudson.test.JenkinsRule)5 VerificationException (com.axway.ats.uiengine.exceptions.VerificationException)4 ConfirmHandler (com.gargoylesoftware.htmlunit.ConfirmHandler)4 Map (java.util.Map)4 JSONObject (net.sf.json.JSONObject)4 RsaJsonWebKey (org.jose4j.jwk.RsaJsonWebKey)4 JsonWebSignature (org.jose4j.jws.JsonWebSignature)4 JwtClaims (org.jose4j.jwt.JwtClaims)4 JwtConsumer (org.jose4j.jwt.consumer.JwtConsumer)4 JwtConsumerBuilder (org.jose4j.jwt.consumer.JwtConsumerBuilder)4 JsonWebStructure (org.jose4j.jwx.JsonWebStructure)4