use of org.apache.http.impl.auth.BasicScheme in project tutorials by eugenp.
the class HttpClientPostingLiveTest method whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect.
@Test
public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws IOException, AuthenticationException {
final CloseableHttpClient client = HttpClients.createDefault();
final HttpPost httpPost = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION);
httpPost.setEntity(new StringEntity("test post"));
final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
httpPost.addHeader(new BasicScheme().authenticate(creds, httpPost, null));
final CloseableHttpResponse response = client.execute(httpPost);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
use of org.apache.http.impl.auth.BasicScheme 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.auth.BasicScheme 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.auth.BasicScheme 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);
}
}
use of org.apache.http.impl.auth.BasicScheme 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);
}
}
Aggregations