use of org.apache.http.auth.AuthSchemeProvider in project ovirt-engine-sdk-java by oVirt.
the class ConnectionBuilder45 method createHttpClient.
/**
* Creates HttpClient
*/
@Override
protected HttpClient createHttpClient() {
int port = getPort();
Lookup<AuthSchemeProvider> authSchemeProvider = null;
CredentialsProvider credsProvider = new BasicCredentialsProvider();
AuthScope authScope = new AuthScope(getHost(), port, AuthScope.ANY_REALM, AuthScope.ANY_SCHEME);
if (user != null && user.length() > 0) {
credsProvider.setCredentials(authScope, new UsernamePasswordCredentials(user, password));
} else if (kerberos) {
authSchemeProvider = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();
credsProvider.setCredentials(authScope, new Credentials() {
@Override
public Principal getUserPrincipal() {
return null;
}
@Override
public String getPassword() {
return null;
}
});
}
RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).setConnectTimeout(timeout).build();
HttpClientBuilder clientBuilder = HttpClientBuilder.create().setConnectionManager(new PoolingHttpClientConnectionManager(createConnectionSocketFactoryRegistry())).setDefaultRequestConfig(globalConfig).setDefaultCredentialsProvider(credsProvider).setDefaultAuthSchemeRegistry(authSchemeProvider);
if (!compress) {
clientBuilder.disableContentCompression();
}
return new HttpClient45(clientBuilder.build());
}
use of org.apache.http.auth.AuthSchemeProvider in project wildfly by wildfly.
the class Utils method makeCallWithBasicAuthn.
/**
* Returns response body for the given URL request as a String. It also checks if the returned HTTP status code is the
* expected one. If the server returns {@link HttpServletResponse#SC_UNAUTHORIZED} and username is provided, then a new
* request is created with the provided credentials (basic authentication).
*
* @param url URL to which the request should be made
* @param user Username (may be null)
* @param pass Password (may be null)
* @param expectedStatusCode expected status code returned from the requested server
* @param checkFollowupAuthState whether to check auth state for followup request - if set to true, followup
* request is sent to server and 200 OK is expected directly (no re-authentication
* challenge - 401 Unauthorized - is expected)
* @return HTTP response body
* @throws IOException
* @throws URISyntaxException
*/
public static String makeCallWithBasicAuthn(URL url, String user, String pass, int expectedStatusCode, boolean checkFollowupAuthState) throws IOException, URISyntaxException {
LOGGER.trace("Requesting URL " + url);
// use UTF-8 charset for credentials
Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.BASIC, new BasicSchemeFactory(StandardCharsets.UTF_8)).register(AuthSchemes.DIGEST, new DigestSchemeFactory(StandardCharsets.UTF_8)).build();
try (CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultAuthSchemeRegistry(authSchemeRegistry).build()) {
final HttpGet httpGet = new HttpGet(url.toURI());
HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) {
assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
return EntityUtils.toString(response.getEntity());
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
}
HttpEntity entity = response.getEntity();
if (entity != null)
EntityUtils.consume(entity);
final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, pass);
HttpClientContext hc = new HttpClientContext();
hc.setCredentialsProvider(new BasicCredentialsProvider());
hc.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), credentials);
// enable auth
response = httpClient.execute(httpGet, hc);
statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, statusCode);
if (checkFollowupAuthState) {
// Let's disable authentication for this client as we already have all the context necessary to be
// authorized (we expect that gained 'nonce' value can be re-used in our case here).
// By disabling authentication we simply get first server response and thus we can check whether we've
// got 200 OK or different response code.
RequestConfig reqConf = RequestConfig.custom().setAuthenticationEnabled(false).build();
httpGet.setConfig(reqConf);
response = httpClient.execute(httpGet, hc);
statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code returned after the authentication.", HttpURLConnection.HTTP_OK, statusCode);
}
return EntityUtils.toString(response.getEntity());
}
}
use of org.apache.http.auth.AuthSchemeProvider in project jmeter by apache.
the class HTTPHC4Impl method setupClient.
private MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager> setupClient(HttpClientKey key, JMeterVariables jMeterVariables, HttpClientContext clientContext) throws GeneralSecurityException {
Map<HttpClientKey, MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager>> mapHttpClientPerHttpClientKey = HTTPCLIENTS_CACHE_PER_THREAD_AND_HTTPCLIENTKEY.get();
clientContext.setAttribute(CONTEXT_ATTRIBUTE_CLIENT_KEY, key);
CloseableHttpClient httpClient = null;
MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager> triple = null;
boolean concurrentDwn = this.testElement.isConcurrentDwn();
Map<String, Object> samplerContext = JMeterContextService.getContext().getSamplerContext();
if (concurrentDwn) {
triple = (MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager>) samplerContext.get(CONTEXT_ATTRIBUTE_PARENT_SAMPLE_CLIENT_STATE);
}
if (triple == null) {
triple = mapHttpClientPerHttpClientKey.get(key);
}
if (triple != null) {
httpClient = triple.getLeft();
}
setupProxyAuthState(triple, clientContext);
resetStateIfNeeded(triple, jMeterVariables, clientContext, mapHttpClientPerHttpClientKey);
if (httpClient == null) {
// One-time init for this client
DnsResolver resolver = this.testElement.getDNSResolver();
if (resolver == null) {
resolver = SystemDefaultDnsResolver.INSTANCE;
}
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", new LazyLayeredConnectionSocketFactory()).register("http", CONNECTION_SOCKET_FACTORY).build();
// Modern browsers use more connections per host than the current httpclient default (2)
// when using parallel download the httpclient and connection manager are shared by the downloads threads
// to be realistic JMeter must set an higher value to DefaultMaxPerRoute
PoolingHttpClientConnectionManager pHCCM = new PoolingHttpClientConnectionManager(new JMeterDefaultHttpClientConnectionOperator(registry, null, resolver), null, TIME_TO_LIVE, TimeUnit.MILLISECONDS);
pHCCM.setValidateAfterInactivity(VALIDITY_AFTER_INACTIVITY_TIMEOUT);
if (concurrentDwn) {
try {
int maxConcurrentDownloads = Integer.parseInt(this.testElement.getConcurrentPool());
pHCCM.setDefaultMaxPerRoute(Math.max(maxConcurrentDownloads, pHCCM.getDefaultMaxPerRoute()));
} catch (NumberFormatException nfe) {
// no need to log -> will be done by the sampler
}
}
CookieSpecProvider cookieSpecProvider = new IgnoreSpecProvider();
Lookup<CookieSpecProvider> cookieSpecRegistry = RegistryBuilder.<CookieSpecProvider>create().register(CookieSpecs.IGNORE_COOKIES, cookieSpecProvider).build();
HttpClientBuilder builder = HttpClients.custom().setConnectionManager(pHCCM).setSchemePortResolver(new DefaultSchemePortResolver()).setDnsResolver(resolver).setRequestExecutor(REQUEST_EXECUTOR).setSSLSocketFactory(new LazyLayeredConnectionSocketFactory()).setDefaultCookieSpecRegistry(cookieSpecRegistry).setDefaultSocketConfig(SocketConfig.DEFAULT).setRedirectStrategy(new LaxRedirectStrategy()).setConnectionTimeToLive(TIME_TO_LIVE, TimeUnit.MILLISECONDS).setRetryHandler(new StandardHttpRequestRetryHandler(RETRY_COUNT, REQUEST_SENT_RETRY_ENABLED)).setConnectionReuseStrategy(DefaultClientConnectionReuseStrategy.INSTANCE).setProxyAuthenticationStrategy(getProxyAuthStrategy());
if (DISABLE_DEFAULT_UA) {
builder.disableDefaultUserAgent();
}
Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.BASIC, new BasicSchemeFactory()).register(AuthSchemes.DIGEST, new DigestSchemeFactory()).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).register(AuthSchemes.SPNEGO, new DynamicSPNegoSchemeFactory(AuthManager.STRIP_PORT, AuthManager.USE_CANONICAL_HOST_NAME)).register(AuthSchemes.KERBEROS, new DynamicKerberosSchemeFactory(AuthManager.STRIP_PORT, AuthManager.USE_CANONICAL_HOST_NAME)).build();
builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
if (IDLE_TIMEOUT > 0) {
builder.setKeepAliveStrategy(IDLE_STRATEGY);
}
// Set up proxy details
AuthScope proxyAuthScope = null;
NTCredentials proxyCredentials = null;
if (key.hasProxy) {
HttpHost proxy = new HttpHost(key.proxyHost, key.proxyPort, key.proxyScheme);
builder.setProxy(proxy);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
if (!key.proxyUser.isEmpty()) {
proxyAuthScope = new AuthScope(key.proxyHost, key.proxyPort);
proxyCredentials = new NTCredentials(key.proxyUser, key.proxyPass, LOCALHOST, PROXY_DOMAIN);
credsProvider.setCredentials(proxyAuthScope, proxyCredentials);
}
builder.setDefaultCredentialsProvider(credsProvider);
}
builder.disableContentCompression().addInterceptorLast(RESPONSE_CONTENT_ENCODING);
if (BASIC_AUTH_PREEMPTIVE) {
builder.addInterceptorFirst(PREEMPTIVE_AUTH_INTERCEPTOR);
} else {
builder.setDefaultCredentialsProvider(new ManagedCredentialsProvider(getAuthManager(), proxyAuthScope, proxyCredentials));
}
httpClient = builder.build();
if (log.isDebugEnabled()) {
log.debug("Created new HttpClient: @{} {}", System.identityHashCode(httpClient), key);
}
triple = MutableTriple.of(httpClient, null, pHCCM);
// save the agent for next time round
mapHttpClientPerHttpClientKey.put(key, triple);
} else {
if (log.isDebugEnabled()) {
log.debug("Reusing the HttpClient: @{} {}", System.identityHashCode(httpClient), key);
}
}
if (concurrentDwn) {
samplerContext.put(CONTEXT_ATTRIBUTE_PARENT_SAMPLE_CLIENT_STATE, triple);
}
return triple;
}
use of org.apache.http.auth.AuthSchemeProvider in project ranger by apache.
the class ElasticSearchMgr method getRestClientBuilder.
public static RestClientBuilder getRestClientBuilder(String urls, String protocol, String user, String password, int port) {
RestClientBuilder restClientBuilder = RestClient.builder(MiscUtil.toArray(urls, ",").stream().map(x -> new HttpHost(x, port, protocol)).<HttpHost>toArray(i -> new HttpHost[i]));
if (StringUtils.isNotBlank(user) && StringUtils.isNotBlank(password) && !user.equalsIgnoreCase("NONE") && !password.equalsIgnoreCase("NONE")) {
if (password.contains("keytab") && new File(password).exists()) {
final KerberosCredentialsProvider credentialsProvider = CredentialsProviderUtil.getKerberosCredentials(user, password);
Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()).build();
restClientBuilder.setHttpClientConfigCallback(clientBuilder -> {
clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
clientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
return clientBuilder;
});
} else {
final CredentialsProvider credentialsProvider = CredentialsProviderUtil.getBasicCredentials(user, password);
restClientBuilder.setHttpClientConfigCallback(clientBuilder -> clientBuilder.setDefaultCredentialsProvider(credentialsProvider));
}
} else {
logger.error("ElasticSearch Credentials not provided!!");
final CredentialsProvider credentialsProvider = null;
restClientBuilder.setHttpClientConfigCallback(clientBuilder -> clientBuilder.setDefaultCredentialsProvider(credentialsProvider));
}
return restClientBuilder;
}
use of org.apache.http.auth.AuthSchemeProvider in project coprhd-controller by CoprHD.
the class WinRMTarget method createHttpClient.
/**
* HttpClient builder
* @return HttpClient
* @throws HttpException
*/
protected CloseableHttpClient createHttpClient() throws HttpException {
HttpClientBuilder httpClient = HttpClientBuilder.create();
// Build the request config identifying the target preferred authentication schemes and other socket connection parameters.
RequestConfig.Builder requestConfig = RequestConfig.custom().setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.SPNEGO, AuthSchemes.NTLM, AuthSchemes.DIGEST, AuthSchemes.BASIC));
requestConfig.setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT);
requestConfig.setSocketTimeout(DEFAULT_CONNECTION_TIMEOUT);
httpClient.setDefaultRequestConfig(requestConfig.build());
// Set the request executor. The EncryptedHttpRequestExecutor is a custom request executor that is capable of encryption and works
// using the Windows NTLM authentication scheme.
httpClient.setRequestExecutor(new EncryptedHttpRequestExecutor());
// Build a list of the authentication schemes
Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.NTLM, new NTLMSchemeFactory()).register(AuthSchemes.BASIC, new BasicSchemeFactory()).register(AuthSchemes.DIGEST, new DigestSchemeFactory()).register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).register(AuthSchemes.SPNEGO, new CustomSPNegoSchemeFactory()).build();
try {
httpClient.setConnectionManager(createClientConnectionManager());
} catch (Exception e) {
throw new HttpException(e.getMessage());
}
httpClient.setDefaultAuthSchemeRegistry(authSchemeRegistry);
return httpClient.build();
}
Aggregations