use of org.apache.http.impl.client.BasicAuthCache in project jbpm by kiegroup.
the class RESTWorkItemHandler method doRequestWithAuthorization.
protected HttpResponse doRequestWithAuthorization(HttpClient httpclient, HttpRequestBase httpMethod, Map<String, Object> params, AuthenticationType type) {
if (type == null || type == AuthenticationType.NONE) {
try {
return httpclient.execute(httpMethod);
} catch (Exception e) {
throw new RuntimeException("Could not execute request [" + httpMethod.getMethod() + "] " + httpMethod.getURI(), e);
}
}
String u = (String) params.get(PARAM_USERNAME);
String p = (String) params.get(PARAM_PASSWORD);
if (u == null || p == null) {
u = this.username;
p = this.password;
}
if (u == null) {
throw new IllegalArgumentException("Could not find username");
}
if (p == null) {
throw new IllegalArgumentException("Could not find password");
}
if (type == AuthenticationType.BASIC) {
HttpHost targetHost = new HttpHost(httpMethod.getURI().getHost(), httpMethod.getURI().getPort(), httpMethod.getURI().getScheme());
((DefaultHttpClient) httpclient).getCredentialsProvider().setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(u, p));
// 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);
try {
return httpclient.execute(targetHost, httpMethod, localcontext);
} catch (Exception e) {
throw new RuntimeException("Could not execute request [" + httpMethod.getMethod() + "] " + httpMethod.getURI(), e);
}
} else if (type == AuthenticationType.FORM_BASED) {
String authUrlStr = (String) params.get(PARAM_AUTHURL);
if (authUrlStr == null) {
authUrlStr = authUrl;
}
if (authUrlStr == null) {
throw new IllegalArgumentException("Could not find authentication url");
}
try {
httpclient.execute(httpMethod);
} catch (IOException e) {
throw new RuntimeException("Could not execute request for form-based authentication", e);
} finally {
httpMethod.releaseConnection();
}
HttpPost authMethod = new HttpPost(authUrlStr);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("j_username", u));
nvps.add(new BasicNameValuePair("j_password", p));
authMethod.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
try {
httpclient.execute(authMethod);
} catch (IOException e) {
throw new RuntimeException("Could not initialize form-based authentication", e);
} finally {
authMethod.releaseConnection();
}
try {
return httpclient.execute(httpMethod);
} catch (Exception e) {
throw new RuntimeException("Could not execute request [" + httpMethod.getMethod() + "] " + httpMethod.getURI(), e);
}
} else {
throw new RuntimeException("Unknown AuthenticationType " + type);
}
}
use of org.apache.http.impl.client.BasicAuthCache in project pentaho-kettle by pentaho.
the class JobEntryHTTP method getResultFromHttpSchema.
private InputStream getResultFromHttpSchema(String realUploadFile, URI uri) throws IOException, KettleException {
HttpClient client = null;
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
if (!Utils.isEmpty(username)) {
String realPassword = Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(password));
String realUser = environmentSubstitute(username);
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(realUser, realPassword != null ? realPassword : "");
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(AuthScope.ANY, credentials);
clientBuilder.setDefaultCredentialsProvider(provider);
}
String proxyHostnameValue = environmentSubstitute(proxyHostname);
String proxyPortValue = environmentSubstitute(proxyPort);
String nonProxyHostsValue = environmentSubstitute(nonProxyHosts);
if (!Utils.isEmpty(proxyHostnameValue)) {
HttpHost proxy = new HttpHost(proxyHostnameValue, Integer.parseInt(proxyPortValue));
clientBuilder.setProxy(proxy);
if (!Utils.isEmpty(nonProxyHostsValue)) {
HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy) {
@Override
public HttpRoute determineRoute(final HttpHost host, final HttpRequest request, final HttpContext context) throws HttpException {
String hostName = host.getHostName();
if (hostName.matches(nonProxyHostsValue)) {
// Return direct route
return new HttpRoute(host);
}
return super.determineRoute(host, request, context);
}
};
clientBuilder.setRoutePlanner(routePlanner);
}
}
client = clientBuilder.build();
HttpRequestBase httpRequestBase;
// See if we need to send a file over?
if (!Utils.isEmpty(realUploadFile)) {
if (log.isDetailed()) {
logDetailed(BaseMessages.getString(PKG, "JobHTTP.Log.SendingFile", realUploadFile));
}
httpRequestBase = new HttpPost(uri);
// Get content of file
String content = new String(Files.readAllBytes(Paths.get(realUploadFile)));
// upload data to web server
StringEntity requestEntity = new StringEntity(content);
requestEntity.setContentType("application/x-www-form-urlencoded");
((HttpPost) httpRequestBase).setEntity(requestEntity);
if (log.isDetailed()) {
logDetailed(BaseMessages.getString(PKG, "JobHTTP.Log.FinishedSendingFile"));
}
} else {
httpRequestBase = new HttpGet(uri);
}
// if we have HTTP headers, add them
if (!Utils.isEmpty(headerName)) {
if (log.isDebug()) {
log.logDebug(BaseMessages.getString(PKG, "JobHTTP.Log.HeadersProvided"));
}
for (int j = 0; j < headerName.length; j++) {
if (!Utils.isEmpty(headerValue[j])) {
httpRequestBase.addHeader(environmentSubstitute(headerName[j]), environmentSubstitute(headerValue[j]));
if (log.isDebug()) {
log.logDebug(BaseMessages.getString(PKG, "JobHTTP.Log.HeaderSet", environmentSubstitute(headerName[j]), environmentSubstitute(headerValue[j])));
}
}
}
}
// Get a stream for the specified URL
HttpResponse response = null;
if (!Utils.isEmpty(proxyHostname)) {
HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
// 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(target, basicAuth);
// Add AuthCache to the execution context
HttpClientContext localContext = HttpClientContext.create();
localContext.setAuthCache(authCache);
response = client.execute(target, httpRequestBase, localContext);
} else {
response = client.execute(httpRequestBase);
}
responseStatusCode = response.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK != responseStatusCode) {
throw new KettleException("StatusCode: " + responseStatusCode);
}
if (log.isDetailed()) {
logDetailed(BaseMessages.getString(PKG, "JobHTTP.Log.StartReadingReply"));
}
logBasic(BaseMessages.getString(PKG, "JobHTTP.Log.ReplayInfo", response.getEntity().getContentType(), response.getLastHeader(HttpHeaders.DATE).getValue()));
// Read the result from the server...
return response.getEntity().getContent();
}
use of org.apache.http.impl.client.BasicAuthCache in project pentaho-kettle by pentaho.
the class HTTP method callHttpService.
@VisibleForTesting
Object[] callHttpService(RowMetaInterface rowMeta, Object[] rowData) throws KettleException {
HttpClientManager.HttpClientBuilderFacade clientBuilder = HttpClientManager.getInstance().createBuilder();
if (data.realConnectionTimeout > -1) {
clientBuilder.setConnectionTimeout(data.realConnectionTimeout);
}
if (data.realSocketTimeout > -1) {
clientBuilder.setSocketTimeout(data.realSocketTimeout);
}
if (StringUtils.isNotBlank(data.realHttpLogin)) {
clientBuilder.setCredentials(data.realHttpLogin, data.realHttpPassword);
}
if (StringUtils.isNotBlank(data.realProxyHost)) {
clientBuilder.setProxy(data.realProxyHost, data.realProxyPort);
}
CloseableHttpClient httpClient = clientBuilder.build();
// Prepare HTTP get
URI uri = null;
try {
URIBuilder uriBuilder = constructUrlBuilder(rowMeta, rowData);
uri = uriBuilder.build();
HttpGet method = new HttpGet(uri);
// Add Custom HTTP headers
if (data.useHeaderParameters) {
for (int i = 0; i < data.header_parameters_nrs.length; i++) {
method.addHeader(data.headerParameters[i].getName(), data.inputRowMeta.getString(rowData, data.header_parameters_nrs[i]));
if (isDebug()) {
log.logDebug(BaseMessages.getString(PKG, "HTTPDialog.Log.HeaderValue", data.headerParameters[i].getName(), data.inputRowMeta.getString(rowData, data.header_parameters_nrs[i])));
}
}
}
Object[] newRow = null;
if (rowData != null) {
newRow = rowData.clone();
}
// Execute request
CloseableHttpResponse httpResponse = null;
try {
// used for calculating the responseTime
long startTime = System.currentTimeMillis();
HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
// 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(target, basicAuth);
// Add AuthCache to the execution context
HttpClientContext localContext = HttpClientContext.create();
localContext.setAuthCache(authCache);
// Preemptive authentication
if (StringUtils.isNotBlank(data.realProxyHost)) {
httpResponse = httpClient.execute(target, method, localContext);
} else {
httpResponse = httpClient.execute(method, localContext);
}
// calculate the responseTime
long responseTime = System.currentTimeMillis() - startTime;
if (log.isDetailed()) {
log.logDetailed(BaseMessages.getString(PKG, "HTTP.Log.ResponseTime", responseTime, uri));
}
int statusCode = requestStatusCode(httpResponse);
// The status code
if (isDebug()) {
logDebug(BaseMessages.getString(PKG, "HTTP.Log.ResponseStatusCode", "" + statusCode));
}
String body;
switch(statusCode) {
case HttpURLConnection.HTTP_UNAUTHORIZED:
throw new KettleStepException(BaseMessages.getString(PKG, "HTTP.Exception.Authentication", data.realUrl));
case -1:
throw new KettleStepException(BaseMessages.getString(PKG, "HTTP.Exception.IllegalStatusCode", data.realUrl));
case HttpURLConnection.HTTP_NO_CONTENT:
body = "";
break;
default:
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
body = StringUtils.isEmpty(meta.getEncoding()) ? EntityUtils.toString(entity) : EntityUtils.toString(entity, meta.getEncoding());
} else {
body = "";
}
break;
}
Header[] headers = searchForHeaders(httpResponse);
JSONObject json = new JSONObject();
for (Header header : headers) {
Object previousValue = json.get(header.getName());
if (previousValue == null) {
json.put(header.getName(), header.getValue());
} else if (previousValue instanceof List) {
List<String> list = (List<String>) previousValue;
list.add(header.getValue());
} else {
ArrayList<String> list = new ArrayList<String>();
list.add((String) previousValue);
list.add(header.getValue());
json.put(header.getName(), list);
}
}
String headerString = json.toJSONString();
int returnFieldsOffset = rowMeta.size();
if (!Utils.isEmpty(meta.getFieldName())) {
newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, body);
returnFieldsOffset++;
}
if (!Utils.isEmpty(meta.getResultCodeFieldName())) {
newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, new Long(statusCode));
returnFieldsOffset++;
}
if (!Utils.isEmpty(meta.getResponseTimeFieldName())) {
newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, new Long(responseTime));
returnFieldsOffset++;
}
if (!Utils.isEmpty(meta.getResponseHeaderFieldName())) {
newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, headerString);
}
} finally {
if (httpResponse != null) {
httpResponse.close();
}
// Release current connection to the connection pool once you are done
method.releaseConnection();
}
return newRow;
} catch (UnknownHostException uhe) {
throw new KettleException(BaseMessages.getString(PKG, "HTTP.Error.UnknownHostException", uhe.getMessage()));
} catch (Exception e) {
throw new KettleException(BaseMessages.getString(PKG, "HTTP.Log.UnableGetResult", uri), e);
}
}
use of org.apache.http.impl.client.BasicAuthCache in project pentaho-kettle by pentaho.
the class HTTPPOST method callHTTPPOST.
private Object[] callHTTPPOST(Object[] rowData) throws KettleException {
HttpClientManager.HttpClientBuilderFacade clientBuilder = HttpClientManager.getInstance().createBuilder();
if (data.realConnectionTimeout > -1) {
clientBuilder.setConnectionTimeout(data.realConnectionTimeout);
}
if (data.realSocketTimeout > -1) {
clientBuilder.setSocketTimeout(data.realSocketTimeout);
}
if (StringUtils.isNotBlank(data.realHttpLogin)) {
clientBuilder.setCredentials(data.realHttpLogin, data.realHttpPassword);
}
if (StringUtils.isNotBlank(data.realProxyHost)) {
clientBuilder.setProxy(data.realProxyHost, data.realProxyPort);
}
CloseableHttpClient httpClient = clientBuilder.build();
// get dynamic url ?
if (meta.isUrlInField()) {
data.realUrl = data.inputRowMeta.getString(rowData, data.indexOfUrlField);
}
// Prepare HTTP POST
FileInputStream fis = null;
try {
if (isDetailed()) {
logDetailed(BaseMessages.getString(PKG, "HTTPPOST.Log.ConnectingToURL", data.realUrl));
}
URIBuilder uriBuilder = new URIBuilder(data.realUrl);
HttpPost post = new HttpPost(uriBuilder.build());
// ISO-8859-1 is assumed by the POSTMethod
if (!data.contentTypeHeaderOverwrite) {
// can be overwritten now
if (Utils.isEmpty(data.realEncoding)) {
post.setHeader(CONTENT_TYPE, CONTENT_TYPE_TEXT_XML);
if (isDebug()) {
logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.HeaderValue", CONTENT_TYPE, CONTENT_TYPE_TEXT_XML));
}
} else {
post.setHeader(CONTENT_TYPE, CONTENT_TYPE_TEXT_XML + "; " + data.realEncoding);
if (isDebug()) {
logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.HeaderValue", CONTENT_TYPE, CONTENT_TYPE_TEXT_XML + "; " + data.realEncoding));
}
}
}
// HEADER PARAMETERS
if (data.useHeaderParameters) {
// set header parameters that we want to send
for (int i = 0; i < data.header_parameters_nrs.length; i++) {
post.addHeader(data.headerParameters[i].getName(), data.inputRowMeta.getString(rowData, data.header_parameters_nrs[i]));
if (isDebug()) {
logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.HeaderValue", data.headerParameters[i].getName(), data.inputRowMeta.getString(rowData, data.header_parameters_nrs[i])));
}
}
}
// BODY PARAMETERS
if (data.useBodyParameters) {
// set body parameters that we want to send
for (int i = 0; i < data.body_parameters_nrs.length; i++) {
String bodyParameterName = data.bodyParameters[i].getName();
String bodyParameterValue = data.inputRowMeta.getString(rowData, data.body_parameters_nrs[i]);
data.bodyParameters[i] = new BasicNameValuePair(bodyParameterName, bodyParameterValue);
if (isDebug()) {
logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.BodyValue", bodyParameterName, bodyParameterValue));
}
}
String bodyParams = getRequestBodyParamsAsStr(data.bodyParameters, data.realEncoding);
post.setEntity((new StringEntity(bodyParams, ContentType.TEXT_XML.withCharset("US-ASCII"))));
}
// QUERY PARAMETERS
if (data.useQueryParameters) {
for (int i = 0; i < data.query_parameters_nrs.length; i++) {
String queryParameterName = data.queryParameters[i].getName();
String queryParameterValue = data.inputRowMeta.getString(rowData, data.query_parameters_nrs[i]);
data.queryParameters[i] = new BasicNameValuePair(queryParameterName, queryParameterValue);
if (isDebug()) {
logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.QueryValue", queryParameterName, queryParameterValue));
}
}
post.setEntity(new UrlEncodedFormEntity(Arrays.asList(data.queryParameters)));
}
// Set request entity?
if (data.indexOfRequestEntity >= 0) {
String tmp = data.inputRowMeta.getString(rowData, data.indexOfRequestEntity);
if (meta.isPostAFile()) {
File input = new File(tmp);
fis = new FileInputStream(input);
post.setEntity(new InputStreamEntity(fis, input.length()));
} else {
byte[] bytes;
if ((data.realEncoding != null) && (data.realEncoding.length() > 0)) {
bytes = tmp.getBytes(data.realEncoding);
} else {
bytes = tmp.getBytes();
}
post.setEntity(new ByteArrayEntity(bytes));
}
}
// Execute request
Object[] newRow = null;
if (rowData != null) {
newRow = rowData.clone();
}
CloseableHttpResponse httpResponse = null;
try {
// used for calculating the responseTime
long startTime = System.currentTimeMillis();
HttpHost target = new HttpHost(uriBuilder.getHost(), uriBuilder.getPort(), uriBuilder.getScheme());
// 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(target, basicAuth);
// Add AuthCache to the execution context
HttpClientContext localContext = HttpClientContext.create();
localContext.setAuthCache(authCache);
// Execute the POST method
if (StringUtils.isNotBlank(data.realProxyHost)) {
httpResponse = httpClient.execute(target, post, localContext);
} else {
httpResponse = httpClient.execute(post, localContext);
}
int statusCode = requestStatusCode(httpResponse);
// calculate the responseTime
long responseTime = System.currentTimeMillis() - startTime;
if (isDetailed()) {
logDetailed(BaseMessages.getString(PKG, "HTTPPOST.Log.ResponseTime", responseTime, data.realUrl));
}
// Display status code
if (isDebug()) {
logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.ResponseCode", String.valueOf(statusCode)));
}
String body;
String headerString = "";
switch(statusCode) {
case HttpURLConnection.HTTP_UNAUTHORIZED:
throw new KettleStepException(BaseMessages.getString(PKG, "HTTPPOST.Exception.Authentication", data.realUrl));
case -1:
throw new KettleStepException(BaseMessages.getString(PKG, "HTTPPOST.Exception.IllegalStatusCode", data.realUrl));
case HttpURLConnection.HTTP_NO_CONTENT:
body = "";
break;
default:
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
body = EntityUtils.toString(entity);
} else {
body = "";
}
Header[] headers = searchForHeaders(httpResponse);
// Use request encoding if specified in component to avoid strange response encodings
// See PDI-3815
JSONObject json = new JSONObject();
for (Header header : headers) {
Object previousValue = json.get(header.getName());
if (previousValue == null) {
json.put(header.getName(), header.getValue());
} else if (previousValue instanceof List) {
List<String> list = (List<String>) previousValue;
list.add(header.getValue());
} else {
ArrayList<String> list = new ArrayList<String>();
list.add((String) previousValue);
list.add(header.getValue());
json.put(header.getName(), list);
}
}
headerString = json.toJSONString();
}
if (isDebug()) {
logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.ResponseBody", body));
}
int returnFieldsOffset = data.inputRowMeta.size();
if (!Utils.isEmpty(meta.getFieldName())) {
newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, body);
returnFieldsOffset++;
}
if (!Utils.isEmpty(meta.getResultCodeFieldName())) {
newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, new Long(statusCode));
returnFieldsOffset++;
}
if (!Utils.isEmpty(meta.getResponseTimeFieldName())) {
newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, new Long(responseTime));
returnFieldsOffset++;
}
if (!Utils.isEmpty(meta.getResponseHeaderFieldName())) {
newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, headerString);
}
} finally {
// Release current connection to the connection pool once you are done
post.releaseConnection();
if (httpResponse != null) {
httpResponse.close();
}
}
return newRow;
} catch (UnknownHostException uhe) {
throw new KettleException(BaseMessages.getString(PKG, "HTTPPOST.Error.UnknownHostException", uhe.getMessage()));
} catch (Exception e) {
throw new KettleException(BaseMessages.getString(PKG, "HTTPPOST.Error.CanNotReadURL", data.realUrl), e);
} finally {
if (fis != null) {
BaseStep.closeQuietly(fis);
}
}
}
use of org.apache.http.impl.client.BasicAuthCache in project knox by apache.
the class KnoxSession method createClient.
@SuppressForbidden
protected 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(clientContext);
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());
/* kerberos auth */
if (clientContext.kerberos().enable()) {
isKerberos = true;
/* set up system properties */
if (!StringUtils.isBlank(clientContext.kerberos().krb5Conf())) {
System.setProperty("java.security.krb5.conf", clientContext.kerberos().krb5Conf());
}
if (!StringUtils.isBlank(clientContext.kerberos().jaasConf())) {
File f = new File(clientContext.kerberos().jaasConf());
if (f.exists()) {
try {
jaasConfigURL = f.getCanonicalFile().toURI().toURL();
LOG.jaasConfigurationLocation(jaasConfigURL.toExternalForm());
} catch (IOException e) {
LOG.failedToLocateJAASConfiguration(e.getMessage());
}
} else {
LOG.jaasConfigurationDoesNotExist(f.getAbsolutePath());
}
}
// Fall back to the default JAAS config
if (jaasConfigURL == null) {
LOG.usingDefaultJAASConfiguration();
jaasConfigURL = getClass().getResource(DEFAULT_JAAS_FILE);
LOG.jaasConfigurationLocation(jaasConfigURL.toExternalForm());
}
if (clientContext.kerberos().debug()) {
System.setProperty("sun.security.krb5.debug", "true");
System.setProperty("sun.security.jgss.debug", "true");
}
// (KNOX-2001) Log a warning if the useSubjectCredsOnly restriction is "relaxed"
String useSubjectCredsOnly = System.getProperty("javax.security.auth.useSubjectCredsOnly");
if (useSubjectCredsOnly != null && !Boolean.parseBoolean(useSubjectCredsOnly)) {
LOG.useSubjectCredsOnlyIsFalse();
}
final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();
return HttpClients.custom().setConnectionManager(connectionManager).setDefaultAuthSchemeRegistry(authSchemeRegistry).setDefaultCredentialsProvider(EMPTY_CREDENTIALS_PROVIDER).build();
} else {
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);
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()));
}
return HttpClients.custom().setConnectionManager(connectionManager).setDefaultCredentialsProvider(credentialsProvider).build();
}
}
Aggregations