List of usage examples for org.apache.http.client.protocol ClientContext AUTH_CACHE
String AUTH_CACHE
To view the source code for org.apache.http.client.protocol ClientContext AUTH_CACHE.
Click Source Link
From source file:org.sonatype.nexus.testsuite.security.nexus4257.Nexus4257CookieVerificationIT.java
@Test public void testCookieForStateFullClient() throws Exception { setAnonymousAccess(false);/*from w w w.j av a 2 s . c o m*/ TestContext context = TestContainer.getInstance().getTestContext(); String username = context.getAdminUsername(); String password = context.getPassword(); String url = this.getBaseNexusUrl() + "content/"; URI nexusBaseURI = new URI(url); DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "SomeUAThatWillMakeMeLookStateful/1.0"); final BasicHttpContext localcontext = new BasicHttpContext(); final HttpHost targetHost = new HttpHost(nexusBaseURI.getHost(), nexusBaseURI.getPort(), nexusBaseURI.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); // stateful clients must login first, since other rest urls create no sessions String loginUrl = this.getBaseNexusUrl() + "service/local/authentication/login"; assertThat(executeAndRelease(httpClient, new HttpGet(loginUrl), localcontext), equalTo(200)); // after login check content but make sure only cookie is used httpClient.getCredentialsProvider().clear(); HttpGet getMethod = new HttpGet(url); assertThat(executeAndRelease(httpClient, getMethod, null), equalTo(200)); Cookie sessionCookie = this.getSessionCookie(httpClient.getCookieStore().getCookies()); assertThat("Session Cookie not set", sessionCookie, notNullValue()); httpClient.getCookieStore().clear(); // remove cookies // do not set the cookie, expect failure HttpGet failedGetMethod = new HttpGet(url); assertThat(executeAndRelease(httpClient, failedGetMethod, null), equalTo(401)); // set the cookie expect a 200, If a cookie is set, and cannot be found on the server, the response will fail // with a 401 httpClient.getCookieStore().addCookie(sessionCookie); getMethod = new HttpGet(url); assertThat(executeAndRelease(httpClient, getMethod, null), equalTo(200)); }
From source file:org.sonatype.nexus.testsuite.security.nexus4383.Nexus4383LogoutResourceIT.java
/** * 1.) Make a get request to set a cookie </BR> * 2.) verify cookie works (do not send basic auth) </BR> * 3.) do logout </BR>/*from w ww.j a v a 2 s .co m*/ * 4.) repeat step 2 and expect failure. */ @Test public void testLogout() throws Exception { TestContext context = TestContainer.getInstance().getTestContext(); String username = context.getAdminUsername(); String password = context.getPassword(); String url = this.getBaseNexusUrl() + RequestFacade.SERVICE_LOCAL + "status"; String logoutUrl = this.getBaseNexusUrl() + RequestFacade.SERVICE_LOCAL + "authentication/logout"; Header userAgentHeader = new BasicHeader("User-Agent", "Something Stateful"); // default useragent is: Jakarta Commons-HttpClient/3.1[\r][\n] DefaultHttpClient httpClient = new DefaultHttpClient(); URI nexusBaseURI = new URI(url); final BasicHttpContext localcontext = new BasicHttpContext(); final HttpHost targetHost = new HttpHost(nexusBaseURI.getHost(), nexusBaseURI.getPort(), nexusBaseURI.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); // HACK: Disable CSRFGuard support for now, its too problematic //String owaspQueryParams = null; HttpGet getMethod = new HttpGet(url); getMethod.addHeader(userAgentHeader); try { CloseableHttpResponse response = httpClient.execute(getMethod, localcontext); // HACK: Disable CSRFGuard support for now, its too problematic //Header owaspCsrfToken = response.getFirstHeader("OWASP_CSRFTOKEN"); //assertThat(owaspCsrfToken, is(notNullValue())); //owaspQueryParams = "?" + owaspCsrfToken.getName() + "=" + owaspCsrfToken.getValue(); Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); } finally { getMethod.reset(); } Cookie sessionCookie = this.getSessionCookie(httpClient.getCookieStore().getCookies()); Assert.assertNotNull("Session Cookie not set", sessionCookie); httpClient.getCookieStore().clear(); // remove cookies httpClient.getCredentialsProvider().clear(); // remove auth // now with just the cookie httpClient.getCookieStore().addCookie(sessionCookie); // HACK: Disable CSRFGuard support for now, its too problematic //getMethod = new HttpGet(url + owaspQueryParams); getMethod = new HttpGet(url); try { Assert.assertEquals(httpClient.execute(getMethod).getStatusLine().getStatusCode(), 200); } finally { getMethod.reset(); } // do logout // HACK: Disable CSRFGuard support for now, its too problematic //HttpGet logoutGetMethod = new HttpGet(logoutUrl + owaspQueryParams); HttpGet logoutGetMethod = new HttpGet(logoutUrl); try { final HttpResponse response = httpClient.execute(logoutGetMethod); Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); Assert.assertEquals("OK", EntityUtils.toString(response.getEntity())); } finally { logoutGetMethod.reset(); } // set cookie again httpClient.getCookieStore().clear(); // remove cookies httpClient.getCredentialsProvider().clear(); // remove auth httpClient.getCookieStore().addCookie(sessionCookie); HttpGet failedGetMethod = new HttpGet(url); try { final HttpResponse response = httpClient.execute(failedGetMethod); Assert.assertEquals(response.getStatusLine().getStatusCode(), 401); } finally { failedGetMethod.reset(); } }
From source file:ua.pp.msk.gradle.http.Client.java
private void init(URL targetURL, String user, String password) throws ClientSslException { this.targetUrl = targetURL; logger.debug("Initializing " + this.getClass().getName() + " with target URL " + targetURL.toString()); HttpHost htHost = new HttpHost(targetUrl.getHost(), targetUrl.getPort(), targetUrl.getProtocol()); AuthCache aCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); aCache.put(htHost, basicAuth);/*from w w w . j av a 2 s. c o m*/ UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password); BasicCredentialsProvider cProvider = new BasicCredentialsProvider(); cProvider.setCredentials(new AuthScope(htHost), creds); logger.debug("Credential provider: " + cProvider.toString()); context = new BasicHttpContext(); ClientContextConfigurer cliCon = new ClientContextConfigurer(context); cliCon.setCredentialsProvider(cProvider); context.setAttribute(ClientContext.AUTH_CACHE, aCache); SSLSocketFactory sslConnectionSocketFactory = null; try { sslConnectionSocketFactory = new SSLSocketFactory(new TrustSelfSignedStrategy(), new NexusHostnameVerifier()); } catch (KeyManagementException ex) { logger.error("Cannot manage secure keys", ex); throw new ClientSslException("Cannot manage secure keys", ex); } catch (KeyStoreException ex) { logger.error("Cannot build SSL context due to KeyStore error", ex); throw new ClientSslException("Cannot build SSL context due to KeyStore error", ex); } catch (NoSuchAlgorithmException ex) { logger.error("Unsupported security algorithm", ex); throw new ClientSslException("Unsupported security algorithm", ex); } catch (UnrecoverableKeyException ex) { logger.error("Unrecoverable key", ex); throw new ClientSslException("Unrecoverrable key", ex); } DefaultHttpClient defClient = new DefaultHttpClient(); defClient.setRedirectStrategy(new NexusRedirectStrategy()); defClient.setCredentialsProvider(cProvider); Scheme https = new Scheme("https", 443, sslConnectionSocketFactory); defClient.getConnectionManager().getSchemeRegistry().register(https); defClient.setTargetAuthenticationStrategy(new TargetAuthenticationStrategy()); client = defClient; }
From source file:org.zenoss.metrics.reporter.HttpPoster.java
private final void postImpl(MetricBatch batch) throws IOException { int size = batch.getMetrics().size(); MetricCollection metrics = new MetricCollection(); metrics.setMetrics(batch.getMetrics()); String json = asJson(metrics); // Add AuthCache to the execution context BasicHttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieJar); if (needsAuth && !authenticated) { AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local // auth cache BasicScheme basicAuth = new BasicScheme(); HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); authCache.put(targetHost, basicAuth); localContext.setAttribute(ClientContext.AUTH_CACHE, authCache); }/*from w w w . ja v a 2 s .c o m*/ post.setEntity(new StringEntity(json, APPLICATION_JSON)); cookieJar.clearExpired(new Date()); httpClient.execute(post, responseHandler, localContext); }
From source file:com.amalto.workbench.utils.HttpClientUtil.java
private static HttpContext getPreemptiveContext(HttpHost targetHost) { AuthCache authCache = new BasicAuthCache(); 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:be.cytomine.client.HttpClient.java
public void connect(String url, String username, String password) throws IOException { isAuthByPrivateKey = false;/* w w w. j av a 2 s . c o m*/ log.info("Connection to " + url + " with login=" + username + " and pass=" + password); URL = new URL(url); targetHost = new HttpHost(URL.getHost(), URL.getPort()); client = new DefaultHttpClient(); // 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 localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); // Set credentials UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password); client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds); }
From source file:org.kaaproject.kaa.server.flume.sink.hdfs.AvroSchemaSource.java
private void initHttpRestClient() { httpClient = new DefaultHttpClient(); restHost = new HttpHost(kaaRestHost, kaaRestPort, "http"); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(restHost, basicAuth);// www . j a va2 s.c om CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(kaaRestHost, kaaRestPort, AuthScope.ANY_REALM), new UsernamePasswordCredentials(kaaRestUser, kaaRestPassword)); httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache); httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider); }
From source file:com.unboundid.scim.sdk.PreemptiveAuthInterceptor.java
/** * {@inheritDoc}/* w w w .ja va2 s. c o m*/ */ @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (target.getPort() < 0) { SchemeRegistry schemeRegistry = (SchemeRegistry) context.getAttribute(ClientContext.SCHEME_REGISTRY); Scheme scheme = schemeRegistry.getScheme(target); target = new HttpHost(target.getHostName(), scheme.resolvePort(target.getPort()), target.getSchemeName()); } AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE); if (authCache == null) { authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(target, basicAuth); context.setAttribute(ClientContext.AUTH_CACHE, authCache); return; } CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); if (credsProvider == null) { return; } final AuthState targetState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); if (targetState != null && targetState.getState() == AuthProtocolState.UNCHALLENGED) { final AuthScheme authScheme = authCache.get(target); if (authScheme != null) { doPreemptiveAuth(target, authScheme, targetState, credsProvider); } } final HttpHost proxy = (HttpHost) context.getAttribute(ExecutionContext.HTTP_PROXY_HOST); final AuthState proxyState = (AuthState) context.getAttribute(ClientContext.PROXY_AUTH_STATE); if (proxy != null && proxyState != null && proxyState.getState() == AuthProtocolState.UNCHALLENGED) { final AuthScheme authScheme = authCache.get(proxy); if (authScheme != null) { doPreemptiveAuth(proxy, authScheme, proxyState, credsProvider); } } }
From source file:ua.pp.msk.cliqr.PostProcessorImpl.java
private void init(URL url, String user, String password) throws ClientSslException { this.targetUrl = url; HttpHost htHost = new HttpHost(targetUrl.getHost(), targetUrl.getPort(), targetUrl.getProtocol()); BasicAuthCache aCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(ChallengeState.TARGET); aCache.put(htHost, basicAuth);// ww w .j a v a 2s.c om UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password); BasicCredentialsProvider cProvider = new BasicCredentialsProvider(); cProvider.setCredentials(new AuthScope(htHost), creds); logger.debug("Credential provider: " + cProvider.toString()); context = new BasicHttpContext(); ClientContextConfigurer cliCon = new ClientContextConfigurer(context); context.setAttribute(ClientContext.AUTH_CACHE, aCache); //context.setAuthCache(aCache); cliCon.setCredentialsProvider(cProvider); //context.setCredentialsProvider(cProvider); SSLSocketFactory sslSocketFactory = null; try { //SSLContext trustySslContext = SSLContextBuilder.create().loadTrustMaterial( new TrustSelfSignedStrategy()).build(); //sslConnectionSocketFactory = new SSLConnectionSocketFactory(trustySslContext, new CliQrHostnameVerifier()); sslSocketFactory = new SSLSocketFactory(new TrustSelfSignedStrategy(), new CliQrHostnameVerifier()); } catch (KeyManagementException ex) { logger.error("Cannot manage secure keys", ex); throw new ClientSslException("Cannot manage secure keys", ex); } catch (KeyStoreException ex) { logger.error("Cannot build SSL context due to KeyStore error", ex); throw new ClientSslException("Cannot build SSL context due to KeyStore error", ex); } catch (NoSuchAlgorithmException ex) { logger.error("Unsupported security algorithm", ex); throw new ClientSslException("Unsupported security algorithm", ex); } catch (UnrecoverableKeyException ex) { logger.error("Unrecoverable key", ex); throw new ClientSslException("Unrecoverrable key", ex); } DefaultHttpClient defClient = new DefaultHttpClient(); defClient.setRedirectStrategy(new CliQrRedirectStrategy()); defClient.setCredentialsProvider(cProvider); Scheme https = new Scheme("https", 443, sslSocketFactory); defClient.getConnectionManager().getSchemeRegistry().register(https); defClient.setTargetAuthenticationStrategy(new TargetAuthenticationStrategy()); client = defClient; }
From source file:ua.pp.msk.cliqr.GetProcessorImpl.java
private void init(URL targetURL, String user, String password) throws ClientSslException { this.targetUrl = targetURL; logger.debug("Initializing " + this.getClass().getName() + " with target URL " + targetURL.toString()); HttpHost htHost = new HttpHost(targetUrl.getHost(), targetUrl.getPort(), targetUrl.getProtocol()); AuthCache aCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); aCache.put(htHost, basicAuth);/*from ww w . j av a2s.c o m*/ UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password); BasicCredentialsProvider cProvider = new BasicCredentialsProvider(); cProvider.setCredentials(new AuthScope(htHost), creds); logger.debug("Credential provider: " + cProvider.toString()); context = new BasicHttpContext(); ClientContextConfigurer cliCon = new ClientContextConfigurer(context); cliCon.setCredentialsProvider(cProvider); context.setAttribute(ClientContext.AUTH_CACHE, aCache); SSLSocketFactory sslConnectionSocketFactory = null; try { sslConnectionSocketFactory = new SSLSocketFactory(new TrustSelfSignedStrategy(), new CliQrHostnameVerifier()); } catch (KeyManagementException ex) { logger.error("Cannot manage secure keys", ex); throw new ClientSslException("Cannot manage secure keys", ex); } catch (KeyStoreException ex) { logger.error("Cannot build SSL context due to KeyStore error", ex); throw new ClientSslException("Cannot build SSL context due to KeyStore error", ex); } catch (NoSuchAlgorithmException ex) { logger.error("Unsupported security algorithm", ex); throw new ClientSslException("Unsupported security algorithm", ex); } catch (UnrecoverableKeyException ex) { logger.error("Unrecoverable key", ex); throw new ClientSslException("Unrecoverrable key", ex); } DefaultHttpClient defClient = new DefaultHttpClient(); defClient.setRedirectStrategy(new CliQrRedirectStrategy()); defClient.setCredentialsProvider(cProvider); Scheme https = new Scheme("https", 443, sslConnectionSocketFactory); defClient.getConnectionManager().getSchemeRegistry().register(https); defClient.setTargetAuthenticationStrategy(new TargetAuthenticationStrategy()); client = defClient; }