use of org.apache.http.impl.auth.BasicScheme in project wildfly by wildfly.
the class ConstraintDrivenAuthModeTestCase method testSecuredResourceWithInvalidCredential.
@Test
public void testSecuredResourceWithInvalidCredential() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "secure.jsp"));
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1", "password2");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, credentials);
request.addHeader(new BasicScheme().authenticate(credentials, request));
try (CloseableHttpClient httpClient = HttpClients.custom().build()) {
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_UNAUTHORIZED, statusCode);
}
}
}
use of org.apache.http.impl.auth.BasicScheme in project vcell by virtualcell.
the class VCellApiClient method authenticate.
public AccessTokenRepresentation authenticate(String userid, String password, boolean alreadyDigested) throws ClientProtocolException, IOException {
// hash the password
String digestedPassword = (alreadyDigested) ? (password) : createdDigestPassword(password);
HttpGet httpget = new HttpGet("https://" + httpHost.getHostName() + ":" + httpHost.getPort() + "/access_token?user_id=" + userid + "&user_password=" + digestedPassword + "&client_id=" + clientID);
if (lg.isInfoEnabled()) {
lg.info("Executing request to retrieve access_token " + httpget.getRequestLine());
}
String responseBody = httpclient.execute(httpget, new VCellStringResponseHandler("authenticate()", httpget));
String accessTokenJson = responseBody;
if (lg.isInfoEnabled()) {
lg.info("returned: " + accessTokenJson);
}
Gson gson = new Gson();
AccessTokenRepresentation accessTokenRep = gson.fromJson(accessTokenJson, AccessTokenRepresentation.class);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(httpHost.getHostName(), httpHost.getPort()), new UsernamePasswordCredentials("access_token", accessTokenRep.getToken()));
// 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(httpHost, basicAuth);
// Add AuthCache to the execution context
httpClientContext = HttpClientContext.create();
httpClientContext.setCredentialsProvider(credsProvider);
httpClientContext.setAuthCache(authCache);
return accessTokenRep;
}
use of org.apache.http.impl.auth.BasicScheme in project qpid-broker-j by apache.
the class QpidRestAPIQueueCreator method getHttpClientContext.
private HttpClientContext getHttpClientContext(final HttpHost management) {
final BasicAuthCache authCache = new BasicAuthCache();
authCache.put(management, new BasicScheme());
HttpClientContext localContext = HttpClientContext.create();
localContext.setAuthCache(authCache);
return localContext;
}
use of org.apache.http.impl.auth.BasicScheme 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.auth.BasicScheme 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);
}
}
Aggregations