use of org.apache.http.impl.auth.BasicScheme in project iaf by ibissource.
the class HttpSenderBase method configure.
public void configure() throws ConfigurationException {
super.configure();
if (!getMethodType().equals("POST")) {
if (!isParamsInUrl()) {
throw new ConfigurationException(getLogPrefix() + "paramsInUrl can only be set to false for methodType POST");
}
if (StringUtils.isNotEmpty(getInputMessageParam())) {
throw new ConfigurationException(getLogPrefix() + "inputMessageParam can only be set for methodType POST");
}
}
Builder requestConfig = RequestConfig.custom();
requestConfig.setConnectTimeout(getTimeout());
requestConfig.setConnectionRequestTimeout(getTimeout());
requestConfig.setSocketTimeout(getTimeout());
if (paramList != null) {
paramList.configure();
if (StringUtils.isNotEmpty(getUrlParam())) {
urlParameter = paramList.findParameter(getUrlParam());
addParameterToSkip(urlParameter);
}
}
if (getMaxConnections() <= 0) {
throw new ConfigurationException(getLogPrefix() + "maxConnections is set to [" + getMaxConnections() + "], which is not enough for adequate operation");
}
try {
if (urlParameter == null) {
if (StringUtils.isEmpty(getUrl())) {
throw new ConfigurationException(getLogPrefix() + "url must be specified, either as attribute, or as parameter");
}
staticUri = getURI(getUrl());
}
URL certificateUrl = null;
URL truststoreUrl = null;
if (!StringUtils.isEmpty(getCertificate())) {
certificateUrl = ClassUtils.getResourceURL(classLoader, getCertificate());
if (certificateUrl == null) {
throw new ConfigurationException(getLogPrefix() + "cannot find URL for certificate resource [" + getCertificate() + "]");
}
log.info(getLogPrefix() + "resolved certificate-URL to [" + certificateUrl.toString() + "]");
}
if (!StringUtils.isEmpty(getTruststore())) {
truststoreUrl = ClassUtils.getResourceURL(classLoader, getTruststore());
if (truststoreUrl == null) {
throw new ConfigurationException(getLogPrefix() + "cannot find URL for truststore resource [" + getTruststore() + "]");
}
log.info(getLogPrefix() + "resolved truststore-URL to [" + truststoreUrl.toString() + "]");
}
if (certificateUrl != null || truststoreUrl != null || allowSelfSignedCertificates) {
AuthSSLProtocolSocketFactoryBase socketfactory;
try {
CredentialFactory certificateCf = new CredentialFactory(getCertificateAuthAlias(), null, getCertificatePassword());
CredentialFactory truststoreCf = new CredentialFactory(getTruststoreAuthAlias(), null, getTruststorePassword());
if (isJdk13Compatibility()) {
socketfactory = new AuthSSLProtocolSocketFactoryForJsse10x(certificateUrl, certificateCf.getPassword(), getKeystoreType(), getKeyManagerAlgorithm(), truststoreUrl, truststoreCf.getPassword(), getTruststoreType(), getTrustManagerAlgorithm(), isAllowSelfSignedCertificates(), isVerifyHostname(), isIgnoreCertificateExpiredException());
} else {
socketfactory = new AuthSSLProtocolSocketFactory(certificateUrl, certificateCf.getPassword(), getKeystoreType(), getKeyManagerAlgorithm(), truststoreUrl, truststoreCf.getPassword(), getTruststoreType(), getTrustManagerAlgorithm(), isAllowSelfSignedCertificates(), isVerifyHostname(), isIgnoreCertificateExpiredException());
}
if (StringUtils.isNotEmpty(getProtocol())) {
socketfactory.setProtocol(getProtocol());
}
socketfactory.initSSLContext();
SSLContext sslContext = (SSLContext) socketfactory.sslContext;
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext);
httpClientBuilder.setSSLSocketFactory(socketFactory);
} catch (Throwable t) {
throw new ConfigurationException(getLogPrefix() + "cannot create or initialize SocketFactory", t);
}
}
credentials = new CredentialFactory(getAuthAlias(), getUserName(), getPassword());
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
if (!StringUtils.isEmpty(credentials.getUsername())) {
String uname;
if (StringUtils.isNotEmpty(getAuthDomain())) {
uname = getAuthDomain() + "\\" + credentials.getUsername();
} else {
uname = credentials.getUsername();
}
credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(uname, credentials.getPassword()));
}
if (StringUtils.isNotEmpty(getProxyHost())) {
HttpHost proxy = new HttpHost(getProxyHost(), getProxyPort());
AuthScope scope = new AuthScope(proxy, getProxyRealm(), AuthScope.ANY_SCHEME);
CredentialFactory pcf = new CredentialFactory(getProxyAuthAlias(), getProxyUserName(), getProxyPassword());
if (StringUtils.isNotEmpty(pcf.getUsername())) {
Credentials credentials = new UsernamePasswordCredentials(pcf.getUsername(), pcf.getPassword());
credentialsProvider.setCredentials(scope, credentials);
}
log.trace("setting credentialProvider [" + credentialsProvider.toString() + "]");
requestConfig.setProxy(proxy);
requestConfig.setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC));
AuthCache authCache = httpClientContext.getAuthCache();
if (authCache == null)
authCache = new BasicAuthCache();
authCache.put(proxy, new BasicScheme());
httpClientContext.setAuthCache(authCache);
httpClientBuilder.setProxy(proxy);
}
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
} catch (URISyntaxException e) {
throw new ConfigurationException(getLogPrefix() + "cannot interpret uri [" + getUrl() + "]");
}
if (StringUtils.isNotEmpty(getStyleSheetName())) {
try {
URL stylesheetURL = ClassUtils.getResourceURL(classLoader, getStyleSheetName());
if (stylesheetURL == null) {
throw new ConfigurationException(getLogPrefix() + "cannot find stylesheet [" + getStyleSheetName() + "]");
}
transformerPool = TransformerPool.getInstance(stylesheetURL);
} catch (IOException e) {
throw new ConfigurationException(getLogPrefix() + "cannot retrieve [" + getStyleSheetName() + "]", e);
} catch (TransformerConfigurationException te) {
throw new ConfigurationException(getLogPrefix() + "got error creating transformer from file [" + getStyleSheetName() + "]", te);
}
}
httpClientBuilder.setDefaultRequestConfig(requestConfig.build());
}
use of org.apache.http.impl.auth.BasicScheme in project camel by apache.
the class HttpProducer method executeMethod.
/**
* Strategy when executing the method (calling the remote server).
*
* @param httpRequest the http Request to execute
* @return the response
* @throws IOException can be thrown
*/
protected HttpResponse executeMethod(HttpUriRequest httpRequest) throws IOException {
HttpContext localContext = new BasicHttpContext();
if (getEndpoint().isAuthenticationPreemptive()) {
BasicScheme basicAuth = new BasicScheme();
localContext.setAttribute("preemptive-auth", basicAuth);
}
if (httpContext != null) {
localContext = new BasicHttpContext(httpContext);
}
return httpClient.execute(httpRequest, localContext);
}
use of org.apache.http.impl.auth.BasicScheme in project tmdm-studio-se by Talend.
the class HttpClientUtil method authenticate.
private static void authenticate(String username, String password, HttpUriRequest request, HttpContext preemptiveContext) {
try {
BasicScheme basicScheme = new BasicScheme();
Header authenticateHeader = basicScheme.authenticate(new UsernamePasswordCredentials(username, password), request, preemptiveContext);
request.addHeader(authenticateHeader);
} catch (AuthenticationException e) {
log.error(e.getMessage(), e);
}
}
use of org.apache.http.impl.auth.BasicScheme in project knox by apache.
the class Hadoop method createClient.
private CloseableHttpClient createClient(ClientContext clientContext) throws GeneralSecurityException {
// SSL
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
TrustStrategy trustStrategy = null;
if (clientContext.connection().secure()) {
hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
} else {
trustStrategy = TrustSelfSignedStrategy.INSTANCE;
System.out.println("**************** WARNING ******************\n" + "This is an insecure client instance and may\n" + "leave the interactions subject to a man in\n" + "the middle attack. Please use the login()\n" + "method instead of loginInsecure() for any\n" + "sensitive or production usecases.\n" + "*******************************************");
}
KeyStore trustStore = getTrustStore();
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore, trustStrategy).build();
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", new SSLConnectionSocketFactory(sslContext, hostnameVerifier)).build();
// Pool
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
connectionManager.setMaxTotal(clientContext.pool().maxTotal());
connectionManager.setDefaultMaxPerRoute(clientContext.pool().defaultMaxPerRoute());
ConnectionConfig connectionConfig = ConnectionConfig.custom().setBufferSize(clientContext.connection().bufferSize()).build();
connectionManager.setDefaultConnectionConfig(connectionConfig);
SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(clientContext.socket().keepalive()).setSoLinger(clientContext.socket().linger()).setSoReuseAddress(clientContext.socket().reuseAddress()).setSoTimeout(clientContext.socket().timeout()).setTcpNoDelay(clientContext.socket().tcpNoDelay()).build();
connectionManager.setDefaultSocketConfig(socketConfig);
// Auth
URI uri = URI.create(clientContext.url());
host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
CredentialsProvider credentialsProvider = null;
if (clientContext.username() != null && clientContext.password() != null) {
credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort()), new UsernamePasswordCredentials(clientContext.username(), clientContext.password()));
AuthCache authCache = new BasicAuthCache();
BasicScheme authScheme = new BasicScheme();
authCache.put(host, authScheme);
context = new BasicHttpContext();
context.setAttribute(org.apache.http.client.protocol.HttpClientContext.AUTH_CACHE, authCache);
}
return HttpClients.custom().setConnectionManager(connectionManager).setDefaultCredentialsProvider(credentialsProvider).build();
}
use of org.apache.http.impl.auth.BasicScheme in project knox by apache.
the class GatewayBasicFuncTest method oozieSubmitJob.
/* GET /oozie/v1/admin/status
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Content-Length: 23
Server: Apache-Coyote/1.1
Date: Thu, 14 Feb 2013 15:49:16 GMT
See: oozie-admin-status.json
*/
/* PUT /oozie/v1/admin/status?safemode=true
TODO
*/
/* GET /oozie/v1/admin/os-env
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Content-Length: 2039
Server: Apache-Coyote/1.1
Date: Thu, 14 Feb 2013 15:51:56 GMT
See: oozie-admin-os-env.json
*/
/* GET /oozie/v1/admin/java-sys-properties
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Content-Length: 3673
Server: Apache-Coyote/1.1
Date: Thu, 14 Feb 2013 15:53:00 GMT
See: oozie-admin-java-sys-properties.json
*/
/* GET /oozie/v1/admin/configuration
HTTP/1.1 200 OK
Transfer-Encoding: Identity
Content-Type: application/json;charset=UTF-8
Server: Apache-Coyote/1.1
Date: Thu, 14 Feb 2013 15:53:31 GMT
See: oozie-admin-configuration.json
*/
/* GET /oozie/v1/admin/instrumentation
HTTP/1.1 200 OK
Transfer-Encoding: Identity
Content-Type: application/json;charset=UTF-8
Server: Apache-Coyote/1.1
Date: Thu, 14 Feb 2013 15:55:43 GMT
See: oozie-admin-instrumentation.json
*/
/* GET /oozie/v1/admin/build-version
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Content-Length: 27
Server: Apache-Coyote/1.1
Date: Thu, 14 Feb 2013 16:08:31 GMT
See: oozie-admin-build-version.json
*/
/* POST /oozie/v1/jobs (request XML; contains URL, response JSON)
Content-Type: application/json;charset=UTF-8
Content-Length: 45
Server: Apache-Coyote/1.1
Date: Thu, 14 Feb 2013 18:10:52 GMT
*/
private String oozieSubmitJob(String user, String password, String request, int status) throws IOException, URISyntaxException {
driver.getMock("OOZIE").expect().method("POST").pathInfo("/v1/jobs").respond().status(HttpStatus.SC_CREATED).content(driver.getResourceBytes("oozie-jobs-submit-response.json")).contentType("application/json");
// System.out.println( "REQUEST LENGTH = " + request.length() );
URL url = new URL(driver.getUrl("OOZIE") + "/v1/jobs?action=start" + (driver.isUseGateway() ? "" : "&user.name=" + user));
HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
HttpClientBuilder builder = HttpClientBuilder.create();
CloseableHttpClient client = builder.build();
HttpClientContext context = HttpClientContext.create();
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(targetHost), new UsernamePasswordCredentials(user, password));
context.setCredentialsProvider(credsProvider);
// 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.setAuthCache(authCache);
HttpPost post = new HttpPost(url.toURI());
// post.getParams().setParameter( "action", "start" );
StringEntity entity = new StringEntity(request, org.apache.http.entity.ContentType.create("application/xml", "UTF-8"));
post.setEntity(entity);
post.setHeader("X-XSRF-Header", "ksdjfhdsjkfhds");
HttpResponse response = client.execute(targetHost, post, context);
assertThat(response.getStatusLine().getStatusCode(), Matchers.is(status));
String json = EntityUtils.toString(response.getEntity());
// String json = given()
// .log().all()
// .auth().preemptive().basic( user, password )
// .queryParam( "action", "start" )
// .contentType( "application/xml;charset=UTF-8" )
// .content( request )
// .then()
// .log().all()
// .statusCode( status )
// .when().post( getUrl( "OOZIE" ) + "/v1/jobs" + ( isUseGateway() ? "" : "?user.name=" + user ) ).asString();
// System.out.println( "JSON=" + json );
String id = JsonPath.from(json).getString("id");
return id;
}
Aggregations