Example usage for org.apache.http.impl.client LaxRedirectStrategy LaxRedirectStrategy

List of usage examples for org.apache.http.impl.client LaxRedirectStrategy LaxRedirectStrategy

Introduction

In this page you can find the example usage for org.apache.http.impl.client LaxRedirectStrategy LaxRedirectStrategy.

Prototype

LaxRedirectStrategy

Source Link

Usage

From source file:com.stratio.qa.utils.GosecSSOUtils.java

/**
 * This method provide dcos and sso token to be used to generate client cookie
 * @return cookieToken list of token generated
 * @throws Exception exception/*from  w w  w  .ja  v  a 2  s  .c  om*/
 */
public HashMap<String, String> ssoTokenGenerator() throws Exception {
    String protocol = "https://";
    HashMap<String, String> cookieToken = new HashMap<>();

    SSLContext sslContext = SSLContext.getInstance("SSL");
    // set up a TrustManager that trusts everything
    sslContext.init(null, ALL_TRUSTING_TRUST_MANAGER, new SecureRandom());
    HttpClientContext context = HttpClientContext.create();
    HttpGet httpGet = new HttpGet(protocol + ssoHost + "/login");
    HttpClient client = HttpClientBuilder.create().setSslcontext(sslContext)
            .setRedirectStrategy(new LaxRedirectStrategy())
            .setDefaultRequestConfig(RequestConfig.custom().setCircularRedirectsAllowed(true).build()).build();
    try {
        HttpResponse firstResponse = client.execute(httpGet, context);

        logger.debug(firstResponse.getStatusLine().toString());
        Document doc = Jsoup.parse(getStringFromIS(firstResponse.getEntity().getContent()));
        Elements code = doc.select("[name=lt]");
        String loginCode = code.attr("value");
        String executionCode = doc.select("[name=execution]").attr("value");
        for (Header oneHeader : firstResponse.getAllHeaders()) {
            logger.debug(oneHeader.getName() + ":" + oneHeader.getValue());
        }

        URI redirect = context.getRedirectLocations().get(context.getRedirectLocations().size() - 1);

        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("_eventId", "submit"));
        params.add(new BasicNameValuePair("submit", "LOGIN"));
        params.add(new BasicNameValuePair("username", userName));
        params.add(new BasicNameValuePair("password", passWord));
        params.add(new BasicNameValuePair("lt", loginCode));
        params.add(new BasicNameValuePair("execution", executionCode));
        HttpPost httpPost = new HttpPost(redirect);
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        HttpResponse secondResponse = client.execute(httpPost, context);

        for (Header oneHeader : secondResponse.getAllHeaders()) {
            logger.debug(oneHeader.getName() + ":" + oneHeader.getValue());
        }

        HttpGet managementGet = new HttpGet(protocol + ssoHost + managementHost);
        client.execute(managementGet, context);

        for (Cookie oneCookie : context.getCookieStore().getCookies()) {
            logger.debug(oneCookie.getName() + ":" + oneCookie.getValue());
            cookieToken.put(oneCookie.getName(), oneCookie.getValue());
        }

    } catch (Exception e) {
        e.getStackTrace();
    }
    return cookieToken;
}

From source file:com.github.jrrdev.mantisbtsync.core.common.auth.PortalAuthManager.java

/**
 * EGet the authenfication by executing the defined requests sequence.
 *
 * @throws IOException/*from w w w . j a  va  2 s  .c  o  m*/
 * @throws ClientProtocolException
 */
public ExitStatus authentificate() throws ClientProtocolException, IOException {
    authCookie = null;

    if (firstRequest != null) {

        final CookieStore cookieStore = new BasicCookieStore();
        client = HttpClients.custom().setDefaultCookieStore(cookieStore)
                .setRedirectStrategy(new LaxRedirectStrategy()).useSystemProperties().build();

        lastResponse = firstRequest.executeSequence(client);

        final List<Cookie> cookies = cookieStore.getCookies();
        final StringBuilder strBuff = new StringBuilder();
        for (final Cookie cookie : cookies) {
            strBuff.append(cookie.getName());
            strBuff.append("=");
            strBuff.append(cookie.getValue());
            strBuff.append(";");
        }

        authCookie = strBuff.toString();
    }

    return ExitStatus.COMPLETED;
}

From source file:org.keycloak.testsuite.crossdc.ConcurrentLoginCrossDCTest.java

@Test
public void concurrentLoginWithRandomDcFailures() throws Throwable {
    log.info("*********************************************");
    long start = System.currentTimeMillis();

    AtomicReference<String> userSessionId = new AtomicReference<>();
    LoginTask loginTask = null;/*  ww  w.j a v  a 2s.  co  m*/

    try (CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setRedirectStrategy(new LaxRedirectStrategy()).build()) {
        loginTask = new LoginTask(httpClient, userSessionId, LOGIN_TASK_DELAY_MS, LOGIN_TASK_RETRIES, false,
                Arrays.asList(createHttpClientContextForUser(httpClient, "test-user@localhost", "password")));
        HttpUriRequest request = handleLogin(
                getPageContent(oauth.getLoginFormUrl(), httpClient, HttpClientContext.create()),
                "test-user@localhost", "password");
        log.debug("Executing login request");
        org.junit.Assert.assertTrue(
                parseAndCloseResponse(httpClient.execute(request)).contains("<title>AUTH_RESPONSE</title>"));

        run(DEFAULT_THREADS, DEFAULT_CLIENTS_COUNT, loginTask, new SwapDcAvailability());
        int clientSessionsCount = testingClient.testing().getClientSessionsCountInUserSession("test",
                userSessionId.get());
        org.junit.Assert.assertEquals(1 + DEFAULT_CLIENTS_COUNT, clientSessionsCount);
    } finally {
        long end = System.currentTimeMillis() - start;
        log.infof("Statistics: %s", loginTask == null ? "??" : loginTask.getHistogram());
        log.info("concurrentLoginWithRandomDcFailures took " + (end / 1000) + "s");
        log.info("*********************************************");
    }
}

From source file:org.lazydevs.api.gog.GogApi.java

public GogApi() {

    this.client = new DefaultHttpClient();
    this.context = new BasicHttpContext();
    this.cookies = new BasicCookieStore();

    this.context.setAttribute(ClientContext.COOKIE_STORE, this.cookies);

    client.setRedirectStrategy(new LaxRedirectStrategy());

    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    /* For capturing traffic with Fiddler
    HttpClientUtil.initHttpsNoCertNoHostVerification(client, 443);
            //from w ww  . jav  a2 s .c  o m
    HttpHost proxy = new HttpHost("localhost", 8888);
            
    client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
     */
}

From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java

public static String sendHttpGet(String url, String user, String password, int returnCodeIDP, int returnCodeRP,
        int idpPort) throws Exception {

    CloseableHttpClient httpClient = null;
    try {/*from   www . ja  v  a 2 s  . co m*/
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope("localhost", idpPort),
                new UsernamePasswordCredentials(user, password));

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks"));
        try {
            trustStore.load(instream, "clientpass".toCharArray());
        } finally {
            try {
                instream.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
        sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray());

        SSLContext sslContext = sslContextBuilder.build();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
        httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
        httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

        httpClient = httpClientBuilder.build();

        HttpGet httpget = new HttpGet(url);

        HttpResponse response = httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
                + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode());

        if (response.getStatusLine().getStatusCode() != 200) {
            return null;
        }

        //            Redirect to a POST is not supported without user interaction
        //            http://www.ietf.org/rfc/rfc2616.txt
        //            If the 301 status code is received in response to a request other
        //            than GET or HEAD, the user agent MUST NOT automatically redirect the
        //            request unless it can be confirmed by the user, since this might
        //            change the conditions under which the request was issued.

        Source source = new Source(EntityUtils.toString(entity));
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        FormFields formFields = source.getFormFields();

        List<Element> forms = source.getAllElements(HTMLElementName.FORM);
        Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size());
        String postUrl = forms.get(0).getAttributeValue("action");

        Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa"));
        Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult"));

        for (FormField formField : formFields) {
            if (formField.getUserValueCount() != 0) {
                nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0)));
            }
        }
        HttpPost httppost = new HttpPost(postUrl);
        httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

        response = httpClient.execute(httppost);

        entity = response.getEntity();
        System.out.println(response.getStatusLine());
        Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
                + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode());

        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }

        return EntityUtils.toString(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

From source file:org.apache.sling.hapi.client.impl.AbstractHtmlClientImpl.java

public AbstractHtmlClientImpl(String baseUrl, String user, String password) throws URISyntaxException {
    this.baseUrl = new URI(baseUrl);
    HttpHost targetHost = URIUtils.extractHost(this.baseUrl);
    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(user, password));
    this.client = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider)
            .setRedirectStrategy(new LaxRedirectStrategy()).build();
}

From source file:edu.kit.dama.staging.adalapi.protocol.SimpleHttp.java

@Override
public final CloseableHttpClient connectProtocolClient() throws AdalapiException {
    final CloseableHttpClient httpclient = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy()) // adds HTTP REDIRECT support to GET and POST methods 
            .build();//from   w w  w .  j av  a2 s  .co  m

    /* AbstractAuthentication auth = getAuthenticationMethod();
            
    if (!auth.isConnected()) {
    LOGGER.debug("Authentication is not connected, requesting user interaction");
    try {
        auth.authenticate();
    } catch (AuthenticationInputMethodException uaim) {
        throw new AdalapiSecurityException("Failed to authenticate", uaim);
    }
    LOGGER.debug("User interaction finished. Trying to connect protocol client");
    }
     */
    return httpclient;
}