Search in sources :

Example 11 with CookieStore

use of org.apache.http.client.CookieStore in project wildfly by wildfly.

the class SSOTestBase method executeFormAuthSingleSignOnTest.

/**
     * Test single sign-on across two web apps using form based auth
     *
     * @throws Exception
     */
public static void executeFormAuthSingleSignOnTest(URL serverA, URL serverB, Logger log) throws Exception {
    URL warA1 = new URL(serverA, "/war1/");
    URL warB2 = new URL(serverB, "/war2/");
    // Start by accessing the secured index.html of war1
    CookieStore store = new BasicCookieStore();
    HttpClient httpclient = TestHttpClientUtils.promiscuousCookieHttpClientBuilder().setDefaultCookieStore(store).disableRedirectHandling().build();
    try {
        checkAccessDenied(httpclient, warA1 + "index.html");
        log.debug("Saw JSESSIONID=" + getSessionIdValueFromState(store));
        // Submit the login form
        executeFormLogin(httpclient, warA1);
        String ssoID = processSSOCookie(store, serverA.toString(), serverB.toString());
        log.debug("Saw JSESSIONIDSSO=" + ssoID);
        // Now try getting the war2 index using the JSESSIONIDSSO cookie
        log.debug("Prepare /war2/index.html get");
        checkAccessAllowed(httpclient, warB2 + "index.html");
        // Access a secured servlet that calls a secured ejb in war2 to test
        // propagation of the SSO identity to the ejb container.
        checkAccessAllowed(httpclient, warB2 + "EJBServlet");
        // Now try logging out of war2
        executeLogout(httpclient, warB2);
    } finally {
        HttpClientUtils.closeQuietly(httpclient);
    }
    try {
        // Reset Http client
        httpclient = HttpClients.createDefault();
        // Try accessing war1 again
        checkAccessDenied(httpclient, warA1 + "index.html");
        // Try accessing war2 again
        checkAccessDenied(httpclient, warB2 + "index.html");
    } finally {
        HttpClientUtils.closeQuietly(httpclient);
    }
}
Also used : CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) HttpClient(org.apache.http.client.HttpClient) URL(java.net.URL)

Example 12 with CookieStore

use of org.apache.http.client.CookieStore in project undertow by undertow-io.

the class ServletSessionCrawlerTestCase method testCrawlerSessionUsage.

@Test
public void testCrawlerSessionUsage() throws IOException, InterruptedException {
    final PathHandler pathHandler = new PathHandler();
    final ServletContainer container = ServletContainer.Factory.newInstance();
    DeploymentInfo builder = new DeploymentInfo().setCrawlerSessionManagerConfig(new CrawlerSessionManagerConfig()).setClassLoader(SimpleServletTestCase.class.getClassLoader()).setContextPath("/servletContext").setClassIntrospecter(TestClassIntrospector.INSTANCE).setDeploymentName("servletContext.war").addListener(new ListenerInfo(SessionCookieConfigListener.class)).addServlets(new ServletInfo("servlet", SessionServlet.class).addMapping("/aa/b"));
    DeploymentManager manager = container.addDeployment(builder);
    manager.deploy();
    try {
        pathHandler.addPrefixPath(builder.getContextPath(), manager.start());
    } catch (ServletException e) {
        throw new RuntimeException(e);
    }
    DefaultServer.setRootHandler(pathHandler);
    TestHttpClient client = new TestHttpClient();
    client.setCookieStore(new CookieStore() {

        @Override
        public void addCookie(Cookie cookie) {
        }

        @Override
        public List<Cookie> getCookies() {
            return Collections.EMPTY_LIST;
        }

        @Override
        public boolean clearExpired(Date date) {
            return false;
        }

        @Override
        public void clear() {
        }
    });
    try {
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/aa/b");
        get.addHeader(Headers.USER_AGENT_STRING, "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        String response = HttpClientUtils.readResponse(result);
        Assert.assertEquals("1", response);
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        response = HttpClientUtils.readResponse(result);
        Assert.assertEquals("2", response);
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        response = HttpClientUtils.readResponse(result);
        Assert.assertEquals("3", response);
    } finally {
        client.getConnectionManager().shutdown();
    }
}
Also used : Cookie(org.apache.http.cookie.Cookie) DeploymentManager(io.undertow.servlet.api.DeploymentManager) HttpGet(org.apache.http.client.methods.HttpGet) PathHandler(io.undertow.server.handlers.PathHandler) HttpResponse(org.apache.http.HttpResponse) Date(java.util.Date) TestHttpClient(io.undertow.testutils.TestHttpClient) ServletInfo(io.undertow.servlet.api.ServletInfo) ServletException(javax.servlet.ServletException) CookieStore(org.apache.http.client.CookieStore) ListenerInfo(io.undertow.servlet.api.ListenerInfo) CrawlerSessionManagerConfig(io.undertow.servlet.api.CrawlerSessionManagerConfig) ServletContainer(io.undertow.servlet.api.ServletContainer) List(java.util.List) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) Test(org.junit.Test)

Example 13 with CookieStore

use of org.apache.http.client.CookieStore in project webmagic by code4craft.

the class HttpClientGenerator method generateCookie.

private void generateCookie(HttpClientBuilder httpClientBuilder, Site site) {
    CookieStore cookieStore = new BasicCookieStore();
    for (Map.Entry<String, String> cookieEntry : site.getCookies().entrySet()) {
        BasicClientCookie cookie = new BasicClientCookie(cookieEntry.getKey(), cookieEntry.getValue());
        cookie.setDomain(site.getDomain());
        cookieStore.addCookie(cookie);
    }
    for (Map.Entry<String, Map<String, String>> domainEntry : site.getAllCookies().entrySet()) {
        for (Map.Entry<String, String> cookieEntry : domainEntry.getValue().entrySet()) {
            BasicClientCookie cookie = new BasicClientCookie(cookieEntry.getKey(), cookieEntry.getValue());
            cookie.setDomain(domainEntry.getKey());
            cookieStore.addCookie(cookie);
        }
    }
    httpClientBuilder.setDefaultCookieStore(cookieStore);
}
Also used : CookieStore(org.apache.http.client.CookieStore) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) Map(java.util.Map)

Example 14 with CookieStore

use of org.apache.http.client.CookieStore in project android-instagram by markchang.

the class LoginActivity method doLogin.

public void doLogin(View view) {
    CookieStore cookieStore;
    // clear cookies
    clearCookies();
    // gather login info
    String password = txtPassword.getText().toString();
    String username = txtUsername.getText().toString();
    if (Utils.isOnline(getApplicationContext()) == false) {
        Toast.makeText(LoginActivity.this, "No connection to Internet.\nTry again later.", Toast.LENGTH_SHORT).show();
        Log.i(Utils.TAG, "No internet, failed Login");
        return;
    }
    // create POST
    HttpPost httpPost = new HttpPost(Utils.LOGIN_URL);
    List<NameValuePair> postParams = new ArrayList<NameValuePair>();
    postParams.add(new BasicNameValuePair("username", username));
    postParams.add(new BasicNameValuePair("password", password));
    postParams.add(new BasicNameValuePair("device_id", "0000"));
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(postParams, HTTP.UTF_8));
        HttpResponse httpResponse = httpClient.execute(httpPost);
        // test result code
        if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            Toast.makeText(LoginActivity.this, "Login failed", Toast.LENGTH_SHORT).show();
            Log.i(TAG, "Login HTTP status fail");
            return;
        }
        // test json response
        HttpEntity httpEntity = httpResponse.getEntity();
        if (httpEntity != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"));
            String json = reader.readLine();
            JSONTokener jsonTokener = new JSONTokener(json);
            JSONObject jsonObject = new JSONObject(jsonTokener);
            Log.i(TAG, "JSON: " + jsonObject.toString());
            String loginStatus = jsonObject.getString("status");
            if (!loginStatus.equals("ok")) {
                Toast.makeText(LoginActivity.this, "Login failed", Toast.LENGTH_SHORT).show();
                Log.e(TAG, "JSON status not ok: " + jsonObject.getString("status"));
                return;
            }
        }
        // save login info so that we can reuse them later
        cookieStore = httpClient.getCookieStore();
        if (saveLoginInfo(cookieStore, username, password) == true) {
            Toast.makeText(LoginActivity.this, "Logged in", Toast.LENGTH_SHORT).show();
            openMainActivity();
        } else {
            Toast.makeText(LoginActivity.this, "Login failed", Toast.LENGTH_SHORT).show();
            Log.e(TAG, "Cookie error");
        }
    } catch (IOException e) {
        Log.e(TAG, "HttpPost error: " + e.toString());
        Toast.makeText(LoginActivity.this, "Login failed " + e.toString(), Toast.LENGTH_LONG).show();
    } catch (JSONException e) {
        Log.e(TAG, "JSON parse error: " + e.toString());
        Toast.makeText(LoginActivity.this, "Result from instagr.am was unexpected: " + e.toString(), Toast.LENGTH_LONG).show();
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpEntity(org.apache.http.HttpEntity) InputStreamReader(java.io.InputStreamReader) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) JSONException(org.json.JSONException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) JSONTokener(org.json.JSONTokener) CookieStore(org.apache.http.client.CookieStore) JSONObject(org.json.JSONObject) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) BufferedReader(java.io.BufferedReader)

Example 15 with CookieStore

use of org.apache.http.client.CookieStore in project openhab1-addons by openhab.

the class Tr064Comm method createTr064HttpClient.

/***
     * Creates a apache HTTP Client object, ignoring SSL Exceptions like self signed certificates
     * and sets Auth. Scheme to Digest Auth
     *
     * @param fboxUrl the URL from config file of fbox to connect to
     * @return the ready-to-use httpclient for tr064 requests
     */
private CloseableHttpClient createTr064HttpClient(String fboxUrl) {
    CloseableHttpClient hc = null;
    // Convert URL String from config in easy explotable URI object
    URIBuilder uriFbox = null;
    try {
        uriFbox = new URIBuilder(fboxUrl);
    } catch (URISyntaxException e) {
        logger.error("Invalid FritzBox URL! {}", e.getMessage());
        return null;
    }
    // Create context of the http client
    _httpClientContext = HttpClientContext.create();
    CookieStore cookieStore = new BasicCookieStore();
    _httpClientContext.setCookieStore(cookieStore);
    // SETUP AUTH
    // Auth is specific for this target
    HttpHost target = new HttpHost(uriFbox.getHost(), uriFbox.getPort(), uriFbox.getScheme());
    // Add digest authentication with username/pw from global config
    CredentialsProvider credp = new BasicCredentialsProvider();
    credp.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(_user, _pw));
    // Create AuthCache instance. Manages authentication based on server response
    AuthCache authCache = new BasicAuthCache();
    // Generate DIGEST scheme object, initialize it and add it to the local auth cache. Digeste is standard for fbox
    // auth SOAP
    DigestScheme digestAuth = new DigestScheme();
    // known from fbox specification
    digestAuth.overrideParamter("realm", "HTTPS Access");
    // never known at first request
    digestAuth.overrideParamter("nonce", "");
    authCache.put(target, digestAuth);
    // Add AuthCache to the execution context
    _httpClientContext.setAuthCache(authCache);
    // SETUP SSL TRUST
    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    SSLConnectionSocketFactory sslsf = null;
    try {
        // accept self signed certs
        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        // dont
        sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), null, null, new NoopHostnameVerifier());
    // verify
    // hostname
    // against
    // cert
    // CN
    } catch (Exception ex) {
        logger.error(ex.getMessage());
    }
    // Set timeout values
    RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(4000).setConnectTimeout(4000).setConnectionRequestTimeout(4000).build();
    // BUILDER
    // setup builder with parameters defined before
    hc = // set the SSL options which trust every self signed
    HttpClientBuilder.create().setSSLSocketFactory(sslsf).setDefaultCredentialsProvider(// set auth options using digest
    credp).setDefaultRequestConfig(// set the request config specifying timeout
    rc).build();
    return hc;
}
Also used : DigestScheme(org.apache.http.impl.auth.DigestScheme) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) URISyntaxException(java.net.URISyntaxException) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) XPathExpressionException(javax.xml.xpath.XPathExpressionException) URISyntaxException(java.net.URISyntaxException) SOAPException(javax.xml.soap.SOAPException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) URIBuilder(org.apache.http.client.utils.URIBuilder) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy)

Aggregations

CookieStore (org.apache.http.client.CookieStore)25 BasicCookieStore (org.apache.http.impl.client.BasicCookieStore)12 IOException (java.io.IOException)7 HttpResponse (org.apache.http.HttpResponse)7 HttpGet (org.apache.http.client.methods.HttpGet)7 HttpHost (org.apache.http.HttpHost)6 CookieOrigin (org.apache.http.cookie.CookieOrigin)6 CookieSpec (org.apache.http.cookie.CookieSpec)6 ArrayList (java.util.ArrayList)5 ClientProtocolException (org.apache.http.client.ClientProtocolException)5 HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)5 Cookie (org.apache.http.cookie.Cookie)5 BasicHttpContext (org.apache.http.protocol.BasicHttpContext)5 Test (org.junit.Test)5 URI (java.net.URI)4 Date (java.util.Date)4 Header (org.apache.http.Header)4 HttpEntity (org.apache.http.HttpEntity)4 HttpClient (org.apache.http.client.HttpClient)4 HttpContext (org.apache.http.protocol.HttpContext)4