Search in sources :

Example 1 with Page

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

the class JwtImplTest method anonymousUserToken.

@Test
public void anonymousUserToken() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    JenkinsRule.WebClient webClient = j.createWebClient();
    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;
    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());
    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("anonymous", 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("anonymous", userContext.get("id"));
}
Also used : JwtClaims(org.jose4j.jwt.JwtClaims) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) 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 2 with Page

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

the class LinkedInOAuthRequestFilter method getRefreshToken.

@SuppressWarnings("deprecation")
private String getRefreshToken() {
    // disable redirect to avoid loading error redirect URL
    webClient.getOptions().setRedirectEnabled(false);
    try {
        final String csrfId = String.valueOf(new SecureRandom().nextLong());
        final String encodedRedirectUri = URLEncoder.encode(oAuthParams.getRedirectUri(), "UTF-8");
        final OAuthScope[] scopes = oAuthParams.getScopes();
        final String url;
        if (scopes == null || scopes.length == 0) {
            url = String.format(AUTHORIZATION_URL, oAuthParams.getClientId(), csrfId, encodedRedirectUri);
        } else {
            final int nScopes = scopes.length;
            final StringBuilder builder = new StringBuilder();
            int i = 0;
            for (OAuthScope scope : scopes) {
                builder.append(scope.getValue());
                if (++i < nScopes) {
                    builder.append("%20");
                }
            }
            url = String.format(AUTHORIZATION_URL_WITH_SCOPE, oAuthParams.getClientId(), csrfId, builder.toString(), encodedRedirectUri);
        }
        HtmlPage authPage;
        try {
            authPage = webClient.getPage(url);
        } catch (FailingHttpStatusCodeException e) {
            // only handle errors returned with redirects
            if (e.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
                final URL location = new URL(e.getResponse().getResponseHeaderValue(HttpHeaders.LOCATION));
                final String locationQuery = location.getQuery();
                if (locationQuery != null && locationQuery.contains("error=")) {
                    throw new IOException(URLDecoder.decode(locationQuery).replaceAll("&", ", "));
                } else {
                    // follow the redirect to login form
                    authPage = webClient.getPage(location);
                }
            } else {
                throw e;
            }
        }
        // look for <div role="alert">
        final HtmlDivision div = authPage.getFirstByXPath("//div[@role='alert']");
        if (div != null) {
            throw new IllegalArgumentException("Error authorizing application: " + div.getTextContent());
        }
        // submit login credentials
        final HtmlForm loginForm = authPage.getFormByName("oauth2SAuthorizeForm");
        final HtmlTextInput login = loginForm.getInputByName("session_key");
        login.setText(oAuthParams.getUserName());
        final HtmlPasswordInput password = loginForm.getInputByName("session_password");
        password.setText(oAuthParams.getUserPassword());
        final HtmlSubmitInput submitInput = loginForm.getInputByName("authorize");
        // validate CSRF and get authorization code
        String redirectQuery;
        try {
            final Page redirectPage = submitInput.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();
        }
        if (redirectQuery == null) {
            throw new IllegalArgumentException("Redirect response query is null, check username, password and permissions");
        }
        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 (!csrfId.equals(state)) {
            throw new SecurityException("Invalid CSRF code!");
        } else {
            // TODO check results??
            return params.get("code");
        }
    } catch (IOException e) {
        throw new IllegalArgumentException("Error authorizing application: " + e.getMessage(), e);
    }
}
Also used : HtmlTextInput(com.gargoylesoftware.htmlunit.html.HtmlTextInput) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) SecureRandom(java.security.SecureRandom) HtmlPasswordInput(com.gargoylesoftware.htmlunit.html.HtmlPasswordInput) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) Page(com.gargoylesoftware.htmlunit.Page) IOException(java.io.IOException) HtmlDivision(com.gargoylesoftware.htmlunit.html.HtmlDivision) URL(java.net.URL) HtmlForm(com.gargoylesoftware.htmlunit.html.HtmlForm) HtmlSubmitInput(com.gargoylesoftware.htmlunit.html.HtmlSubmitInput) FailingHttpStatusCodeException(com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException)

Example 3 with Page

use of com.gargoylesoftware.htmlunit.Page in project Payara by payara.

the class InplantedTest method testWeb.

@Test
public void testWeb() throws Exception {
    System.out.println("test web");
    File f = new File(System.getProperty("basedir"));
    f = new File(f, "target");
    f = new File(f, "test-classes");
    ScatteredArchive.Builder builder = new ScatteredArchive.Builder("hello", f);
    builder.addClassPath(f.toURI().toURL());
    builder.resources(f);
    ScatteredArchive war = builder.buildWar();
    System.out.println("War content");
    Enumeration<String> contents = war.entries();
    while (contents.hasMoreElements()) {
        System.out.println(contents.nextElement());
    }
    Port http = server.createPort(8080);
    ContainerBuilder b = server.createConfig(ContainerBuilder.Type.web);
    server.addContainer(b);
    EmbeddedWebContainer embedded = (EmbeddedWebContainer) b.create(server);
    embedded.bind(http, "http");
    DeployCommandParameters dp = new DeployCommandParameters(f);
    String appName = server.getDeployer().deploy(war, dp);
    WebClient webClient = new WebClient();
    Page page = webClient.getPage("http://localhost:8080/test-classes/hello");
    System.out.println("Got response " + page.getWebResponse().getContentAsString());
    Assert.assertTrue("Servlet returned wrong content", page.getWebResponse().getContentAsString().startsWith("Hello World"));
    server.getDeployer().undeploy(appName, null);
}
Also used : DeployCommandParameters(org.glassfish.api.deployment.DeployCommandParameters) EmbeddedWebContainer(org.glassfish.api.embedded.web.EmbeddedWebContainer) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) Page(com.gargoylesoftware.htmlunit.Page) File(java.io.File) WebClient(com.gargoylesoftware.htmlunit.WebClient) Test(org.junit.Test)

Example 4 with Page

use of com.gargoylesoftware.htmlunit.Page in project JSCover by tntim96.

the class HtmlUnitServerTest method shouldNotInstrument.

@Test
public void shouldNotInstrument() throws Exception {
    Page page = webClient.getPage("http://localhost:9001/example/lib/noInstrument.js");
    assertThat(page.getWebResponse().getContentAsString(), equalTo("alert('Hey');"));
}
Also used : HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) Page(com.gargoylesoftware.htmlunit.Page) Test(org.junit.Test)

Example 5 with Page

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

the class Weld1037Test method testRedirectInPreRenderViewAction.

@Test
@RunAsClient
public void testRedirectInPreRenderViewAction(@ArquillianResource URL url) throws Exception {
    WebClient client = new WebClient();
    client.setRedirectEnabled(false);
    client.setThrowExceptionOnFailingStatusCode(false);
    Page page = client.getPage(url + "/doRedirect.faces");
    assertEquals("Expected redirect:", HttpServletResponse.SC_MOVED_TEMPORARILY, page.getWebResponse().getStatusCode());
}
Also used : Page(com.gargoylesoftware.htmlunit.Page) WebClient(com.gargoylesoftware.htmlunit.WebClient) RunAsClient(org.jboss.arquillian.container.test.api.RunAsClient) Test(org.junit.Test)

Aggregations

Page (com.gargoylesoftware.htmlunit.Page)61 Test (org.junit.Test)39 WebClient (com.gargoylesoftware.htmlunit.WebClient)33 HtmlPage (com.gargoylesoftware.htmlunit.html.HtmlPage)14 PublicAtsApi (com.axway.ats.common.PublicAtsApi)9 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 HtmlForm (com.gargoylesoftware.htmlunit.html.HtmlForm)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 Test (org.junit.jupiter.api.Test)4