use of org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider in project mercury by yellow013.
the class ClientPreemptiveDigestAuthentication method main.
public static void main(final String[] args) throws Exception {
try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {
final HttpHost target = new HttpHost("http", "httpbin.org", 80);
final HttpClientContext localContext = HttpClientContext.create();
final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(target), new UsernamePasswordCredentials("user", "passwd".toCharArray()));
localContext.setCredentialsProvider(credentialsProvider);
final HttpGet httpget = new HttpGet("http://httpbin.org/digest-auth/auth/user/passwd");
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
for (int i = 0; i < 3; i++) {
try (final CloseableHttpResponse response = httpclient.execute(target, httpget, localContext)) {
System.out.println("----------------------------------------");
System.out.println(response.getCode() + " " + response.getReasonPhrase());
EntityUtils.consume(response.getEntity());
final AuthExchange authExchange = localContext.getAuthExchange(target);
if (authExchange != null) {
final AuthScheme authScheme = authExchange.getAuthScheme();
if (authScheme instanceof DigestScheme) {
final DigestScheme digestScheme = (DigestScheme) authScheme;
System.out.println("Nonce: " + digestScheme.getNonce() + "; count: " + digestScheme.getNounceCount());
}
}
}
}
}
}
use of org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider in project webdrivermanager by bonigarcia.
the class HttpClient method createBasicCredentialsProvider.
private final Optional<BasicCredentialsProvider> createBasicCredentialsProvider(String proxy, String proxyUser, String proxyPass, HttpHost proxyHost) throws MalformedURLException, UnsupportedEncodingException {
Optional<URL> proxyUrl = determineProxyUrl(proxy);
if (!proxyUrl.isPresent()) {
return empty();
}
String username = null;
String password = null;
// apply env value
String userInfo = proxyUrl.get().getUserInfo();
if (userInfo != null) {
StringTokenizer st = new StringTokenizer(userInfo, ":");
username = st.hasMoreTokens() ? decode(st.nextToken(), UTF_8.name()) : null;
password = st.hasMoreTokens() ? decode(st.nextToken(), UTF_8.name()) : null;
}
String envProxyUser = getenv("HTTPS_PROXY_USER");
String envProxyPass = getenv("HTTPS_PROXY_PASS");
username = (envProxyUser != null) ? envProxyUser : username;
password = (envProxyPass != null) ? envProxyPass : password;
// apply option value
username = isNullOrEmpty(proxyUser) ? username : proxyUser;
password = isNullOrEmpty(proxyPass) ? password : proxyPass;
if (username == null) {
return empty();
}
String ntlmUsername = username;
String ntlmDomain = null;
int index = username.indexOf('\\');
if (index > 0) {
ntlmDomain = username.substring(0, index);
ntlmUsername = username.substring(index + 1);
}
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
AuthScope authScope = new AuthScope(proxyHost, null, NTLM);
char[] passwd = (password == null) ? new char[0] : password.toCharArray();
Credentials creds = new NTCredentials(ntlmUsername, passwd, getWorkstation(), ntlmDomain);
credentialsProvider.setCredentials(authScope, creds);
authScope = new AuthScope(proxyHost.getHostName(), proxyHost.getPort());
creds = new UsernamePasswordCredentials(username, passwd);
credentialsProvider.setCredentials(authScope, creds);
return Optional.of(credentialsProvider);
}
use of org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider in project wiremock by wiremock.
the class HttpClientFactory method createClient.
public static CloseableHttpClient createClient(int maxConnections, int timeoutMilliseconds, ProxySettings proxySettings, KeyStoreSettings trustStoreSettings, boolean trustSelfSignedCertificates, final List<String> trustedHosts, boolean useSystemProperties) {
HttpClientBuilder builder = HttpClientBuilder.create().disableAuthCaching().disableAutomaticRetries().disableCookieManagement().disableRedirectHandling().disableContentCompression().setConnectionManager(PoolingHttpClientConnectionManagerBuilder.create().setMaxConnPerRoute(maxConnections).setMaxConnTotal(maxConnections).setValidateAfterInactivity(// TODO Verify duration
TimeValue.ofSeconds(5)).setConnectionFactory(new ManagedHttpClientConnectionFactory(null, CharCodingConfig.custom().setCharset(UTF_8).build(), null)).build()).setDefaultRequestConfig(RequestConfig.custom().setResponseTimeout(Timeout.ofMilliseconds(timeoutMilliseconds)).build()).setConnectionReuseStrategy((request, response, context) -> false).setKeepAliveStrategy((response, context) -> TimeValue.ZERO_MILLISECONDS);
if (useSystemProperties) {
builder.useSystemProperties();
}
if (proxySettings != NO_PROXY) {
HttpHost proxyHost = new HttpHost(proxySettings.host(), proxySettings.port());
builder.setProxy(proxyHost);
if (!isEmpty(proxySettings.getUsername()) && !isEmpty(proxySettings.getPassword())) {
// TODO Verify
builder.setProxyAuthenticationStrategy(new DefaultAuthenticationStrategy());
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(proxySettings.host(), proxySettings.port()), new UsernamePasswordCredentials(proxySettings.getUsername(), proxySettings.getPassword().toCharArray()));
builder.setDefaultCredentialsProvider(credentialsProvider);
}
}
final SSLContext sslContext = buildSslContext(trustStoreSettings, trustSelfSignedCertificates, trustedHosts);
LayeredConnectionSocketFactory sslSocketFactory = buildSslConnectionSocketFactory(sslContext);
PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create().setSSLSocketFactory(sslSocketFactory).build();
builder.setConnectionManager(connectionManager);
return builder.build();
}
use of org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider in project commons-vfs by apache.
the class Http5FileProvider method createHttpClientContext.
/**
* Create an {@link HttpClientContext} object for an http4 file system.
*
* @param builder Configuration options builder for http4 provider
* @param rootName The root path
* @param fileSystemOptions The FileSystem options
* @param authData The {@code UserAuthentiationData} object
* @return an {@link HttpClientContext} object
*/
protected HttpClientContext createHttpClientContext(final Http5FileSystemConfigBuilder builder, final GenericFileName rootName, final FileSystemOptions fileSystemOptions, final UserAuthenticationData authData) {
final HttpClientContext clientContext = HttpClientContext.create();
final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
clientContext.setCredentialsProvider(credsProvider);
final String username = UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(rootName.getUserName())));
final char[] password = UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(rootName.getPassword()));
if (!StringUtils.isEmpty(username)) {
// set root port
credsProvider.setCredentials(new AuthScope(rootName.getHostName(), rootName.getPort()), new UsernamePasswordCredentials(username, password));
}
final HttpHost proxyHost = getProxyHttpHost(builder, fileSystemOptions);
if (proxyHost != null) {
final UserAuthenticator proxyAuth = builder.getProxyAuthenticator(fileSystemOptions);
if (proxyAuth != null) {
final UserAuthenticationData proxyAuthData = UserAuthenticatorUtils.authenticate(proxyAuth, new UserAuthenticationData.Type[] { UserAuthenticationData.USERNAME, UserAuthenticationData.PASSWORD });
if (proxyAuthData != null) {
final UsernamePasswordCredentials proxyCreds = new UsernamePasswordCredentials(UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(proxyAuthData, UserAuthenticationData.USERNAME, null)), UserAuthenticatorUtils.getData(proxyAuthData, UserAuthenticationData.PASSWORD, null));
// set proxy host port
credsProvider.setCredentials(new AuthScope(proxyHost.getHostName(), proxyHost.getPort()), proxyCreds);
}
if (builder.isPreemptiveAuth(fileSystemOptions)) {
final AuthCache authCache = new BasicAuthCache();
final BasicScheme basicAuth = new BasicScheme();
authCache.put(proxyHost, basicAuth);
clientContext.setAuthCache(authCache);
}
}
}
return clientContext;
}
use of org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider in project geo-platform by geosdi.
the class DigestPreemptiveSecurityConnector method bindCredentials.
/**
* @param targetHost
* @param targetURI
* @throws Exception
*/
@Override
protected void bindCredentials(@Nonnull(when = NEVER) HttpHost targetHost, @Nonnull(when = NEVER) URI targetURI) throws Exception {
super.bindCredentials(targetHost, targetURI);
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(targetHost), this.usernamePasswordCredentials);
localContext.setCredentialsProvider(credentialsProvider);
}
Aggregations