Example usage for org.apache.http.client.protocol ClientContext AUTH_CACHE

List of usage examples for org.apache.http.client.protocol ClientContext AUTH_CACHE

Introduction

In this page you can find the example usage for org.apache.http.client.protocol ClientContext AUTH_CACHE.

Prototype

String AUTH_CACHE

To view the source code for org.apache.http.client.protocol ClientContext AUTH_CACHE.

Click Source Link

Document

Attribute name of a org.apache.http.client.AuthCache object that represents the auth scheme cache.

Usage

From source file:org.sonatype.nexus.testsuite.security.nexus4257.Nexus4257CookieVerificationIT.java

/**
 * Makes a request after setting the user agent and verifies that the session cookie is NOT set.
 *//*from   w  ww  . jav a2 s.  c om*/
private void testCookieNotSetForKnownStateLessClients(final String userAgent) throws Exception {
    TestContext context = TestContainer.getInstance().getTestContext();
    String username = context.getAdminUsername();
    String password = context.getPassword();
    String url = this.getBaseNexusUrl() + "content/";
    URI uri = new URI(url);

    Header header = new BasicHeader("User-Agent", userAgent + "/1.6"); // user agent plus some version

    DefaultHttpClient httpClient = new DefaultHttpClient();

    final BasicHttpContext localcontext = new BasicHttpContext();
    final HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpGet getMethod = new HttpGet(url);
    getMethod.addHeader(header);
    assertThat(executeAndRelease(httpClient, getMethod, localcontext), equalTo(200));

    Cookie sessionCookie = this.getSessionCookie(httpClient.getCookieStore().getCookies());
    assertThat("Session Cookie should not be set for user agent: " + userAgent, sessionCookie, nullValue());
}

From source file:org.hibernate.ogm.datastore.couchdb.test.dialect.authenticated.AuthenticatedAccessTest.java

private static ResteasyClient getClientWithServerAdminCredentials() {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, port),
            new UsernamePasswordCredentials(serverAdminUser, serverAdminPassword));

    AuthCache authCache = new BasicAuthCache();
    authCache.put(new HttpHost(host, port, "http"), new BasicScheme());

    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    return new ResteasyClientBuilder().httpEngine(new ApacheHttpClient4Engine(httpClient, localContext))
            .build();/*from   w  w  w .j av a  2  s.  com*/
}

From source file:org.ops4j.pax.web.itest.base.client.HttpComponentsWrapper.java

private HttpResponse getHttpResponse(String path, boolean authenticate, BasicHttpContext basicHttpContext,
        boolean async) throws IOException, KeyManagementException, UnrecoverableKeyException,
        NoSuchAlgorithmException, KeyStoreException, CertificateException, AuthenticationException,
        InterruptedException, ExecutionException {

    HttpHost targetHost = getHttpHost(path);

    BasicHttpContext localcontext = basicHttpContext == null ? new BasicHttpContext() : basicHttpContext;

    HttpGet httpget = new HttpGet(path);
    for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
        LOG.info("adding request-header: {}={}", entry.getKey(), entry.getValue());
        httpget.addHeader(entry.getKey(), entry.getValue());
    }/*from w  w  w  .  j a va2  s .  c o m*/

    LOG.info("calling remote {} ...", path);
    HttpResponse response = null;
    if (!authenticate && basicHttpContext == null) {
        if (localcontext.getAttribute(ClientContext.AUTH_CACHE) != null) {
            localcontext.removeAttribute(ClientContext.AUTH_CACHE);
        }
        if (!async) {
            response = httpclient.execute(httpget, context);
        } else {
            Future<HttpResponse> future = httpAsyncClient.execute(httpget, context, null);
            response = future.get();
        }
    } else {
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth
        // cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
        httpget.addHeader(basicAuth.authenticate(creds, httpget, localcontext));
        if (!async) {
            response = httpclient.execute(targetHost, httpget, localcontext);
        } else {
            Future<HttpResponse> future = httpAsyncClient.execute(targetHost, httpget, localcontext, null);
            response = future.get();
        }
    }

    LOG.info("... responded with: {}", response.getStatusLine().getStatusCode());
    return response;
}

From source file:com.glodon.paas.document.api.AbstractDocumentAPITest.java

private void setAuthCache(HttpHost host, BasicHttpContext context) {
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);/* w  ww.  j  a  va 2  s . c o  m*/
    if (context == null && localcontext != null)
        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    else
        context.setAttribute(ClientContext.AUTH_CACHE, authCache);
}

From source file:com.anaplan.client.transport.ApacheHttpProvider.java

/** {@inheritDoc} */
@Override// www  . ja  va 2 s.  com
public void setServiceCredentials(Credentials serviceCredentials) throws AnaplanAPITransportException {

    super.setServiceCredentials(serviceCredentials);

    if (getServiceLocation() != null) {
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicScheme = new BasicScheme();
        authCache.put(httpHost, basicScheme);
        httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    }
}

From source file:gov.nrel.bacnet.consumer.DatabusSender.java

BasicHttpContext setupPreEmptiveBasicAuth(DefaultHttpClient httpclient) {
    HttpHost targetHost = new HttpHost(host, port, mode);
    httpclient.getCredentialsProvider().setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, key));

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    // Add AuthCache to the execution context
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    return localcontext;
}

From source file:org.jspringbot.keyword.http.HTTPHelper.java

/**
 * Set Basic Authentication//from  www.  j  av a 2  s. co  m
 * @param username
 * @param password
 */
public void setBasicAuthentication(String username, String password) {
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);

    client.getCredentialsProvider()
            .setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), credentials);

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();

    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    LOG.createAppender().appendBold("Set Basic Authentication:").appendProperty("Username", username)
            .appendProperty("Password", password).log();

    context.setAttribute(ClientContext.AUTH_CACHE, authCache);
}

From source file:com.cloudbees.tomcat.valves.PrivateAppValveIntegratedTest.java

@Test
public void pre_emptive_basic_authentication_scenario() throws IOException {
    System.out.println("pre_emptive_basic_authentication_scenario");

    privateAppValve.setAuthenticationEntryPoint(PrivateAppValve.AuthenticationEntryPoint.BASIC_AUTH);

    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(httpHost.getHostName(), httpHost.getPort()),
            new UsernamePasswordCredentials(accessKey, secretKey));

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(httpHost, basicAuth);/*  w  w  w  .  j  av a 2 s.co m*/

    // Add AuthCache to the execution context
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpGet httpget = new HttpGet("/");

    for (int i = 0; i < 3; i++) {
        HttpResponse response = httpClient.execute(httpHost, httpget, localcontext);
        assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpServletResponse.SC_OK));
        assertThat(response.containsHeader("x-response"), is(true));

        dumpHttpResponse(response);

        EntityUtils.consumeQuietly(response.getEntity());
    }

}

From source file:com.cloudbees.servlet.filters.PrivateAppFilterIntegratedTest.java

@Test
public void pre_emptive_basic_authentication_scenario() throws IOException {
    System.out.println("pre_emptive_basic_authentication_scenario");

    privateAppFilter.setAuthenticationEntryPoint(PrivateAppFilter.AuthenticationEntryPoint.BASIC_AUTH);

    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(httpHost.getHostName(), httpHost.getPort()),
            new UsernamePasswordCredentials(accessKey, secretKey));

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(httpHost, basicAuth);/*from  ww  w .  j a  va 2s.c  o  m*/

    // Add AuthCache to the execution context
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpGet httpget = new HttpGet("/");

    for (int i = 0; i < 3; i++) {
        HttpResponse response = httpClient.execute(httpHost, httpget, localcontext);
        assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpServletResponse.SC_OK));
        assertThat(response.containsHeader("x-response"), is(true));

        dumpHttpResponse(response);

        EntityUtils.consumeQuietly(response.getEntity());
    }

}