List of usage examples for org.apache.http.client AuthCache put
void put(HttpHost host, AuthScheme authScheme);
From source file:com.consol.citrus.http.client.BasicAuthClientHttpRequestFactory.java
/** * Construct the client factory bean with user credentials. *///from w w w . j a v a2 s . c o m public HttpComponentsClientHttpRequestFactory getObject() throws Exception { Assert.notNull(credentials, "User credentials not set properly!"); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient) { @Override protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { // we have to use preemptive authentication // therefore add some basic auth cache to the local context AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(new HttpHost(authScope.getHost(), authScope.getPort(), "http"), basicAuth); authCache.put(new HttpHost(authScope.getHost(), authScope.getPort(), "https"), basicAuth); BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); return localcontext; } }; if (httpClient instanceof AbstractHttpClient) { ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope, credentials); } else { log.warn("Unable to set username password credentials for basic authentication, " + "because nested HttpClient implementation does not support a credentials provider!"); } return requestFactory; }
From source file:org.nebula.framework.client.NebulaRestClient.java
private HttpClientContext createPreemptiveBasicAuthentication(String accessId, String password) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(accessId, password)); AuthCache authCache = new BasicAuthCache(); authCache.put(target, new BasicScheme()); // Add AuthCache to the execution context HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache);/* w w w . j ava2s . c o m*/ return context; }
From source file:org.apache.geode.rest.internal.web.RestSecurityDUnitTest.java
private HttpResponse doRequest(HttpRequestBase request, String username, String password) throws MalformedURLException { HttpHost targetHost = new HttpHost(HOSTNAME, this.restPort, PROTOCOL); CloseableHttpClient httpclient = HttpClients.custom().build(); HttpClientContext clientContext = HttpClientContext.create(); // if username is null, do not put in authentication if (username != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password)); httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); clientContext.setCredentialsProvider(credsProvider); clientContext.setAuthCache(authCache); }/*from www . ja v a 2 s.co m*/ try { return httpclient.execute(targetHost, request, clientContext); } catch (ClientProtocolException e) { e.printStackTrace(); fail("Rest GET should not have thrown ClientProtocolException!"); } catch (IOException e) { e.printStackTrace(); fail("Rest GET Request should not have thrown IOException!"); } return null; }
From source file:org.artificer.test.AbstractIntegrationTest.java
protected ClientRequest clientRequest(String endpoint) { DefaultHttpClient client = new DefaultHttpClient(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(USERNAME, PASSWORD); client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); HttpHost targetHost = new HttpHost(HOST, PORT); authCache.put(targetHost, basicAuth); BasicHttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.AUTH_CACHE, authCache); ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(client, localContext); ClientRequest clientRequest = new ClientRequest(BASE_URL + endpoint, executor); return clientRequest; }
From source file:org.xwiki.contrib.jira.macro.internal.source.HTTPJIRAFetcher.java
private void setPreemptiveBasicAuthentication(HttpClientContext context, JIRAServer jiraServer, HttpHost targetHost) {//from w w w . ja v a 2 s .com // Connect to JIRA using basic authentication if username and password are defined // Note: Set up preemptive basic authentication since JIRA can accept both unauthenticated and authenticated // requests. See https://developer.atlassian.com/server/jira/platform/basic-authentication/ if (StringUtils.isNotBlank(jiraServer.getUsername()) && StringUtils.isNotBlank(jiraServer.getPassword())) { CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(jiraServer.getUsername(), jiraServer.getPassword())); // 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 context.setCredentialsProvider(provider); context.setAuthCache(authCache); } }
From source file:magicware.scm.redmine.tools.RedmineClient.java
public void fillBasicAuth(String userName, String base64Pwd) { // Basic?/*from w w w.jav a 2 s.c o m*/ httpclient.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(userName, StringUtils.isEmpty(base64Pwd) ? UUID.randomUUID().toString() : new String(Base64.decodeBase64(base64Pwd)))); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); }
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>/* ww w . j av a2s. 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.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); 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 {/*from ww w. j a v a 2s . c om*/ 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; }
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); 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 {//from w ww. j a v a2s.c o m 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.nekorp.workflow.desktop.rest.util.RestTemplateFactory.java
@PostConstruct public void init() { targetHost = new HttpHost(host, port, protocol); //connectionPool = new PoolingHttpClientConnectionManager(); //connectionPool.setDefaultMaxPerRoute(10); //connectionPool.setMaxTotal(20); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password)); //wildcard ssl certificate SSLContext sslContext = SSLContexts.createDefault(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider) //.setConnectionManager(connectionPool) .setSSLSocketFactory(sslsf).build(); // 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 HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactoryBasicAuth( httpclient, localContext);//from w ww .ja va 2 s.co m this.template = new RestTemplate(); template.getMessageConverters().add(new BufferedImageHttpMessageConverter()); template.setRequestFactory(factory); }