Search in sources :

Example 1 with FailingHttpStatusCodeException

use of com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException 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 2 with FailingHttpStatusCodeException

use of com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException in project javaee7-samples by javaee-samples.

the class SecureServletTest method testPutMethod.

@Test
public void testPutMethod() throws Exception {
    webClient.setCredentialsProvider(correctCreds);
    WebRequest request = new WebRequest(new URL(base + "SecureServlet"), HttpMethod.PUT);
    try {
        TextPage p = webClient.getPage(request);
        System.out.println(p.getContent());
    } catch (FailingHttpStatusCodeException e) {
        assertNotNull(e);
        assertEquals(403, e.getStatusCode());
        return;
    }
    fail("PUT method could be called even with deny-unocvered-http-methods");
}
Also used : WebRequest(com.gargoylesoftware.htmlunit.WebRequest) FailingHttpStatusCodeException(com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException) TextPage(com.gargoylesoftware.htmlunit.TextPage) URL(java.net.URL) Test(org.junit.Test)

Example 3 with FailingHttpStatusCodeException

use of com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException in project javaee7-samples by javaee-samples.

the class SecureServletTest method testPostWithIncorrectCredentials.

@Test
public void testPostWithIncorrectCredentials() throws Exception {
    webClient.setCredentialsProvider(correctCreds);
    WebRequest request = new WebRequest(new URL(base + "SecureServlet"), HttpMethod.POST);
    try {
        webClient.getPage(request);
    } catch (FailingHttpStatusCodeException e) {
        assertNotNull(e);
        assertEquals(403, e.getStatusCode());
    }
    fail("/SecureServlet could be accessed without proper security credentials");
}
Also used : WebRequest(com.gargoylesoftware.htmlunit.WebRequest) FailingHttpStatusCodeException(com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException) URL(java.net.URL) Test(org.junit.Test)

Example 4 with FailingHttpStatusCodeException

use of com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException in project javaee7-samples by javaee-samples.

the class SecureServletTest method testPostWithIncorrectCredentials.

@Test
public void testPostWithIncorrectCredentials() throws Exception {
    webClient.setCredentialsProvider(incorrectCreds);
    WebRequest request = new WebRequest(new URL(base + "/SecureServlet"), HttpMethod.POST);
    try {
        webClient.getPage(request);
    } catch (FailingHttpStatusCodeException e) {
        assertNotNull(e);
        assertEquals(401, e.getStatusCode());
        return;
    }
    fail("/SecureServlet could be accessed without proper security credentials");
}
Also used : WebRequest(com.gargoylesoftware.htmlunit.WebRequest) FailingHttpStatusCodeException(com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException) URL(java.net.URL) Test(org.junit.Test)

Example 5 with FailingHttpStatusCodeException

use of com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException in project javaee7-samples by javaee-samples.

the class SecureServletTest method testPostMethod.

@Test
public void testPostMethod() throws Exception {
    webClient.setCredentialsProvider(correctCreds);
    WebRequest request = new WebRequest(new URL(base + "SecureServlet"), HttpMethod.POST);
    try {
        TextPage p = webClient.getPage(request);
        System.out.println(p.getContent());
    } catch (FailingHttpStatusCodeException e) {
        assertNotNull(e);
        assertEquals(403, e.getStatusCode());
        return;
    }
    fail("POST method could be called even with deny-unocvered-http-methods");
}
Also used : WebRequest(com.gargoylesoftware.htmlunit.WebRequest) FailingHttpStatusCodeException(com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException) TextPage(com.gargoylesoftware.htmlunit.TextPage) URL(java.net.URL) Test(org.junit.Test)

Aggregations

FailingHttpStatusCodeException (com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException)7 URL (java.net.URL)6 WebRequest (com.gargoylesoftware.htmlunit.WebRequest)5 Test (org.junit.Test)4 IOException (java.io.IOException)3 Page (com.gargoylesoftware.htmlunit.Page)2 TextPage (com.gargoylesoftware.htmlunit.TextPage)2 HtmlDivision (com.gargoylesoftware.htmlunit.html.HtmlDivision)2 HtmlForm (com.gargoylesoftware.htmlunit.html.HtmlForm)2 HtmlPage (com.gargoylesoftware.htmlunit.html.HtmlPage)2 HtmlPasswordInput (com.gargoylesoftware.htmlunit.html.HtmlPasswordInput)2 HtmlSubmitInput (com.gargoylesoftware.htmlunit.html.HtmlSubmitInput)2 HtmlTextInput (com.gargoylesoftware.htmlunit.html.HtmlTextInput)2 SecureRandom (java.security.SecureRandom)2 HashMap (java.util.HashMap)2 Matcher (java.util.regex.Matcher)2 HtmlUnit (cn.virde.nymph.net.html.HtmlUnit)1 BoxAPIConnection (com.box.sdk.BoxAPIConnection)1 BoxAPIException (com.box.sdk.BoxAPIException)1 ProxyConfig (com.gargoylesoftware.htmlunit.ProxyConfig)1