use of org.apache.http.impl.client.BasicAuthCache in project acceptance-test-harness by jenkinsci.
the class HttpUtils method buildHttpClientContext.
public static HttpClientContext buildHttpClientContext(@Nonnull URL url, @CheckForNull Credentials credentials) {
HttpClientContext context = HttpClientContext.create();
if (credentials != null) {
HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
AuthCache authCache = new BasicAuthCache();
authCache.put(targetHost, new BasicScheme());
// Add AuthCache to the execution context
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, credentials);
context.setCredentialsProvider(credentialsProvider);
context.setAuthCache(authCache);
}
return context;
}
use of org.apache.http.impl.client.BasicAuthCache in project tutorials by eugenp.
the class HttpClientAuthLiveTest method context.
private HttpContext context() {
final HttpHost targetHost = new HttpHost("localhost", 8080, "http");
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS));
// Create AuthCache instance
final AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
authCache.put(targetHost, new BasicScheme());
// Add AuthCache to the execution context
final HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
return context;
}
use of org.apache.http.impl.client.BasicAuthCache in project nuxeo-filesystem-connectors by nuxeo.
the class WebDavClientTest method setUpClass.
@BeforeClass
public static void setUpClass() {
// credentials
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USERNAME, PASSWORD));
// AuthCache instance for preemptive authentication
AuthCache authCache = new BasicAuthCache();
authCache.put(new HttpHost("localhost", WebDavServerFeature.PORT), new BasicScheme());
// create context
context = HttpClientContext.create();
context.setCredentialsProvider(credentialsProvider);
context.setAuthCache(authCache);
// create client
client = HttpClients.createDefault();
}
use of org.apache.http.impl.client.BasicAuthCache in project fabric-sdk-java by hyperledger.
the class HFCAClient method httpPost.
/**
* Http Post Request.
*
* @param url Target URL to POST to.
* @param body Body to be sent with the post.
* @param credentials Credentials to use for basic auth.
* @return Body of post returned.
* @throws Exception
*/
String httpPost(String url, String body, UsernamePasswordCredentials credentials) throws Exception {
logger.debug(format("httpPost %s, body:%s", url, body));
final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
CredentialsProvider provider = null;
if (credentials != null) {
provider = new BasicCredentialsProvider();
provider.setCredentials(AuthScope.ANY, credentials);
httpClientBuilder.setDefaultCredentialsProvider(provider);
}
if (registry != null) {
httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager(registry));
}
HttpClient client = httpClientBuilder.build();
HttpPost httpPost = new HttpPost(url);
AuthCache authCache = new BasicAuthCache();
HttpHost targetHost = new HttpHost(httpPost.getURI().getHost(), httpPost.getURI().getPort());
if (credentials != null) {
authCache.put(targetHost, new BasicScheme());
}
final HttpClientContext context = HttpClientContext.create();
if (null != provider) {
context.setCredentialsProvider(provider);
}
if (credentials != null) {
context.setAuthCache(authCache);
}
httpPost.setEntity(new StringEntity(body));
if (credentials != null) {
httpPost.addHeader(new BasicScheme().authenticate(credentials, httpPost, context));
}
HttpResponse response = client.execute(httpPost, context);
int status = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
logger.trace(format("httpPost %s sending...", url));
String responseBody = entity != null ? EntityUtils.toString(entity) : null;
logger.trace(format("httpPost %s responseBody %s", url, responseBody));
if (status >= 400) {
Exception e = new Exception(format("POST request to %s with request body: %s, " + "failed with status code: %d. Response: %s", url, body, status, responseBody));
logger.error(e.getMessage());
throw e;
}
logger.debug(format("httpPost Status: %d returning: %s ", status, responseBody));
return responseBody;
}
use of org.apache.http.impl.client.BasicAuthCache in project jbpm by kiegroup.
the class RESTWorkItemHandler method doRequestWithAuthorization.
/**
* This method does the actual request, including the setup for authorization.
* </p>
* It is <b>not</b> responsible for cleaning up after the last request that it does.
* </p>
* It <i>is</i> responsible for cleaning up after all previous request, such as for form-based authentication, that happen.
* @param httpclient The {@link HttpClient} instance
* @param requestBuilder The {@link RequestBuilder} instance
* @param params The parameters that may be needed for authentication
* @return A {@link HttpResponse} instance from which we can extract the content
*/
protected HttpResponse doRequestWithAuthorization(HttpClient httpclient, RequestBuilder requestBuilder, Map<String, Object> params, AuthenticationType type) {
// no authorization
if (type == null || type == AuthenticationType.NONE) {
HttpUriRequest request = requestBuilder.build();
try {
return httpclient.execute(request);
} catch (Exception e) {
throw new RuntimeException("Could not execute request [" + request.getMethod() + "] " + request.getURI(), e);
}
}
// user/password
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) {
// basic auth
URI requestUri = requestBuilder.getUri();
HttpHost targetHost = new HttpHost(requestUri.getHost(), requestUri.getPort(), requestUri.getScheme());
// Create AuthCache instance and add it: so that HttpClient thinks that it has already queried (as per the HTTP spec)
// - generate BASIC scheme object and add it to the local auth cache
AuthCache authCache = new BasicAuthCache();
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
// - add AuthCache to the execution context:
HttpClientContext clientContext = HttpClientContext.create();
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(// specify host and port, since that is safer/more secure
new AuthScope(requestUri.getHost(), requestUri.getPort(), AuthScope.ANY_REALM), new UsernamePasswordCredentials(u, p));
clientContext.setCredentialsProvider(credsProvider);
clientContext.setAuthCache(authCache);
// - execute request
HttpUriRequest request = requestBuilder.build();
try {
return httpclient.execute(targetHost, request, clientContext);
} catch (Exception e) {
throw new RuntimeException("Could not execute request with preemptive authentication [" + request.getMethod() + "] " + request.getURI(), e);
}
} else if (type == AuthenticationType.FORM_BASED) {
// form auth
// 1. do initial request to trigger authentication
HttpUriRequest request = requestBuilder.build();
int statusCode = -1;
try {
HttpResponse initialResponse = httpclient.execute(request);
statusCode = initialResponse.getStatusLine().getStatusCode();
} catch (IOException e) {
throw new RuntimeException("Could not execute request for form-based authentication", e);
} finally {
// weird, but this is the method that releases resources, including the connection
request.abort();
}
// See: www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2
if (statusCode != HttpStatus.SC_UNAUTHORIZED) {
logger.error("Expected form authentication request with status {} but status on response is {}: proceeding anyways", HttpStatus.SC_UNAUTHORIZED, statusCode);
}
// 2. do POST form request to authentiate
String authUrlStr = (String) params.get(PARAM_AUTHURL);
if (authUrlStr == null) {
authUrlStr = authUrl;
}
if (authUrlStr == null) {
throw new IllegalArgumentException("Could not find authentication url");
}
HttpPost authMethod = new HttpPost(authUrlStr);
List<NameValuePair> formParams = new ArrayList<NameValuePair>(2);
formParams.add(new BasicNameValuePair("j_username", u));
formParams.add(new BasicNameValuePair("j_password", p));
UrlEncodedFormEntity formEntity;
try {
formEntity = new UrlEncodedFormEntity(formParams);
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("Could not encode authentication parameters into request body", uee);
}
authMethod.setEntity(formEntity);
try {
httpclient.execute(authMethod);
} catch (IOException e) {
throw new RuntimeException("Could not initialize form-based authentication", e);
} finally {
authMethod.releaseConnection();
}
// 3. rebuild request and execute
request = requestBuilder.build();
try {
return httpclient.execute(request);
} catch (Exception e) {
throw new RuntimeException("Could not execute request [" + request.getMethod() + "] " + request.getURI(), e);
}
} else {
throw new RuntimeException("Unknown AuthenticationType " + type);
}
}
Aggregations