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"));
}
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);
}
}
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);
}
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');"));
}
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());
}
Aggregations