List of usage examples for org.apache.http.auth UsernamePasswordCredentials UsernamePasswordCredentials
public UsernamePasswordCredentials(final String userName, final String password)
From source file:org.mule.test.integration.security.HttpListenerAuthenticationTestCase.java
private CredentialsProvider getCredentialsProvider(String user, String password) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password)); return credsProvider; }
From source file:io.wcm.caravan.commons.httpasyncclient.impl.HttpAsyncClientItem.java
/** * @param config Http client configuration */// www.j a v a2 s. co m HttpAsyncClientItem(HttpClientConfig config) { this.config = config; // optional SSL client certificate support SSLContext sslContext; if (CertificateLoader.isSslKeyManagerEnabled(config) || CertificateLoader.isSslTrustStoreEnbaled(config)) { try { sslContext = CertificateLoader.buildSSLContext(config); } catch (IOException | GeneralSecurityException ex) { throw new IllegalArgumentException("Invalid SSL client certificate configuration.", ex); } } else { sslContext = CertificateLoader.createDefaultSSlContext(); } CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); // optional proxy authentication if (StringUtils.isNotEmpty(config.getProxyUser())) { credentialsProvider.setCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort()), new UsernamePasswordCredentials(config.getProxyUser(), config.getProxyPassword())); } // optional http basic authentication support if (StringUtils.isNotEmpty(config.getHttpUser())) { credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(config.getHttpUser(), config.getHttpPassword())); } // build http clients asyncConnectionManager = buildAsyncConnectionManager(config, sslContext); httpAsyncClient = buildHttpAsyncClient(config, asyncConnectionManager, credentialsProvider); // start async client httpAsyncClient.start(); }
From source file:it.cloudicaro.disit.kb.rdf.HttpUtil.java
public static String post(URL url, String data, String contentType, String user, String passwd) throws Exception { //System.out.println("POST "+url); HttpClient client = HttpClients.createDefault(); HttpPost request = new HttpPost(url.toURI()); request.setEntity(new StringEntity(data, ContentType.create(contentType, "UTF-8"))); HttpClientContext context = HttpClientContext.create(); if (user != null && passwd != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, passwd)); context.setCredentialsProvider(credsProvider); }//from w w w .j av a 2 s . com HttpResponse response = client.execute(request, context); StatusLine s = response.getStatusLine(); int code = s.getStatusCode(); //System.out.println(code); if (code == 204) return ""; if (code != 200) throw new Exception( "failed access to " + url.toString() + " code: " + code + " " + s.getReasonPhrase()); Reader reader = null; try { reader = new InputStreamReader(response.getEntity().getContent()); StringBuilder sb = new StringBuilder(); { int read; char[] cbuf = new char[1024]; while ((read = reader.read(cbuf)) != -1) { sb.append(cbuf, 0, read); } } return sb.toString(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:ca.uhn.fhir.rest.client.apache.ApacheRestfulClientFactory.java
public synchronized HttpClient getNativeHttpClient() { if (myHttpClient == null) { PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); connectionManager.setMaxTotal(getPoolMaxTotal()); connectionManager.setDefaultMaxPerRoute(getPoolMaxPerRoute()); // @formatter:off RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(getSocketTimeout()) .setConnectTimeout(getConnectTimeout()) .setConnectionRequestTimeout(getConnectionRequestTimeout()).setStaleConnectionCheckEnabled(true) .setProxy(myProxy).build(); HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager) .setDefaultRequestConfig(defaultRequestConfig).disableCookieManagement(); if (myProxy != null && StringUtils.isNotBlank(getProxyUsername()) && StringUtils.isNotBlank(getProxyPassword())) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(myProxy.getHostName(), myProxy.getPort()), new UsernamePasswordCredentials(getProxyUsername(), getProxyPassword())); builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()); builder.setDefaultCredentialsProvider(credsProvider); }//from w w w. j ava 2s. c o m myHttpClient = builder.build(); // @formatter:on } return myHttpClient; }
From source file:com.expressui.domain.RestClientService.java
/** * Create a REST client// w w w . j a va 2 s . c o m * * @param uri uri of the service * @param clazz client class * @param <T> class type * @return REST client * @throws Exception */ public <T> T create(String uri, Class<T> clazz) throws Exception { RestClientProxyFactoryBean restClientFactory = new RestClientProxyFactoryBean(); restClientFactory.setBaseUri(new URI(uri)); restClientFactory.setServiceInterface(clazz); if (applicationProperties.getHttpProxyHost() != null && applicationProperties.getHttpProxyPort() != null) { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpHost proxy = new HttpHost(applicationProperties.getHttpProxyHost(), applicationProperties.getHttpProxyPort()); if (applicationProperties.getHttpProxyUsername() != null && applicationProperties.getHttpProxyPassword() != null) { httpClient.getCredentialsProvider().setCredentials( new AuthScope(applicationProperties.getHttpProxyHost(), applicationProperties.getHttpProxyPort()), new UsernamePasswordCredentials(applicationProperties.getHttpProxyUsername(), applicationProperties.getHttpProxyPassword())); } httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); restClientFactory.setHttpClient(httpClient); } restClientFactory.afterPropertiesSet(); return (T) restClientFactory.getObject(); }
From source file:org.qi4j.library.shiro.UsernamePasswordHttpBasicTest.java
@Test public void test() throws IOException { HttpGet get = new HttpGet(SECURED_SERVLET_PATH); ResponseHandler<String> responseHandler = new BasicResponseHandler(); DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials(new AuthScope(httpHost.getHostName(), httpHost.getPort()), new UsernamePasswordCredentials(UsernameFixtures.USERNAME, new String(UsernameFixtures.PASSWORD))); // First request with credentials String response = client.execute(httpHost, get, responseHandler); assertEquals(ServletUsingSecuredService.OK, response); // Cookies logging for the curious soutCookies(client.getCookieStore().getCookies()); // Second request without credentials, should work thanks to sessions client.getCredentialsProvider().clear(); response = client.execute(httpHost, get, responseHandler); assertEquals(ServletUsingSecuredService.OK, response); }
From source file:de.perdian.apps.dashboard.support.clients.JsonClient.java
/** * Executes the given job and return the response * * @param requestUri//from ww w . j a v a 2 s. c o m * the URI to which the request should be sent * @return * the JSON result */ public JsonNode sendRequest(CharSequence requestUri) { try { HttpGet httpGet = new HttpGet(requestUri.toString()); if (this.getUsername() != null && this.getPassword() != null) { httpGet.addHeader(new BasicScheme().authenticate( new UsernamePasswordCredentials(this.getUsername(), this.getPassword()), httpGet, new BasicHttpContext())); } for (Map.Entry<Object, Object> defaultHeaderEntry : this.getDefaultHeaders().entrySet()) { httpGet.addHeader((String) defaultHeaderEntry.getKey(), (String) defaultHeaderEntry.getValue()); } String httpResponseString = this.getHttpClient().execute(httpGet, new BasicResponseHandler()); return JsonUtil.fromJsonString(httpResponseString); } catch (Exception e) { StringBuilder errorMessage = new StringBuilder(); errorMessage.append("Cannot send HTTP request [").append(requestUri); errorMessage.append("] using client [").append(this).append("]"); log.debug(errorMessage.toString(), e); throw new DashboardException(errorMessage.toString(), e); } }
From source file:com.katsu.springframework.security.authentication.dni.HttpDniAuthenticationDao.java
private Collection<? extends GrantedAuthority> doLogin(URL url, String username, String password, String dni) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = null;//from w ww .ja v a 2 s. c om HttpResponse httpResponse = null; HttpEntity entity = null; try { httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(username, password)); URIBuilder urib = new URIBuilder(url.toURI().toASCIIString()); urib.addParameter("dni", dni); httpget = new HttpGet(urib.build()); httpResponse = httpclient.execute(httpget); entity = httpResponse.getEntity(); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { logger.trace(httpResponse.getStatusLine().toString()); String body = new java.util.Scanner(new InputStreamReader(entity.getContent())).useDelimiter("\\A") .next(); List<? extends GrantedAuthority> roles = json.deserialize(body, new TypeToken<List<Role>>() { }.getType()); if (roles != null && roles.size() > 0 && roles.get(0).getAuthority() == null) { roles = json.deserialize(body, new TypeToken<List<Role1>>() { }.getType()); } return roles; } else { throw new Exception(httpResponse.getStatusLine().getStatusCode() + " Http code response."); } } catch (Exception e) { if (entity != null) { logger.error(log(entity.getContent()), e); } else { logger.error(e); } throw e; } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:org.springframework.data.solr.HttpSolrClientFactoryTests.java
@Test public void testInitFactoryWithAuthentication() { HttpSolrClientFactory factory = new HttpSolrClientFactory(solrClient, "core", new UsernamePasswordCredentials("username", "password"), "BASIC"); AbstractHttpClient solrHttpClient = (AbstractHttpClient) ((HttpSolrClient) factory.getSolrClient()) .getHttpClient();//from w w w. j av a 2s . com Assert.assertNotNull(solrHttpClient.getCredentialsProvider().getCredentials(AuthScope.ANY)); Assert.assertNotNull(solrHttpClient.getParams().getParameter(AuthPNames.TARGET_AUTH_PREF)); Assert.assertEquals("username", ((UsernamePasswordCredentials) solrHttpClient.getCredentialsProvider() .getCredentials(AuthScope.ANY)).getUserName()); Assert.assertEquals("password", ((UsernamePasswordCredentials) solrHttpClient.getCredentialsProvider() .getCredentials(AuthScope.ANY)).getPassword()); }
From source file:org.apache.nifi.processors.standard.util.HTTPUtils.java
public static void setProxy(final ProcessContext context, final HttpClientBuilder clientBuilder, final CredentialsProvider credentialsProvider) { // Set the proxy if specified final ProxyConfiguration proxyConfig = ProxyConfiguration.getConfiguration(context, () -> { if (context.getProperty(PROXY_HOST).isSet() && context.getProperty(PROXY_PORT).isSet()) { final ProxyConfiguration componentProxyConfig = new ProxyConfiguration(); final String host = context.getProperty(PROXY_HOST).getValue(); final int port = context.getProperty(PROXY_PORT).asInteger(); componentProxyConfig.setProxyType(Proxy.Type.HTTP); componentProxyConfig.setProxyServerHost(host); componentProxyConfig.setProxyServerPort(port); return componentProxyConfig; }//w ww. j a v a 2 s. c o m return ProxyConfiguration.DIRECT_CONFIGURATION; }); if (Proxy.Type.HTTP.equals(proxyConfig.getProxyType())) { final String host = proxyConfig.getProxyServerHost(); final int port = proxyConfig.getProxyServerPort(); clientBuilder.setProxy(new HttpHost(host, port)); if (proxyConfig.hasCredential()) { final AuthScope proxyAuthScope = new AuthScope(host, port); final UsernamePasswordCredentials proxyCredential = new UsernamePasswordCredentials( proxyConfig.getProxyUserName(), proxyConfig.getProxyUserPassword()); credentialsProvider.setCredentials(proxyAuthScope, proxyCredential); } } }