use of org.apache.http.auth.NTCredentials in project selenium_java by sergueik.
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 = (proxyUser != null) ? proxyUser : username;
password = (proxyPass != null) ? proxyPass : password;
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.getHostName(), proxyHost.getPort(), ANY_REALM, NTLM);
Credentials creds = new NTCredentials(ntlmUsername, password, getWorkstation(), ntlmDomain);
credentialsProvider.setCredentials(authScope, creds);
authScope = new AuthScope(proxyHost.getHostName(), proxyHost.getPort());
creds = new UsernamePasswordCredentials(username, password);
credentialsProvider.setCredentials(authScope, creds);
return Optional.of(credentialsProvider);
}
use of org.apache.http.auth.NTCredentials in project axis-axis2-java-core by apache.
the class HTTPProxyConfigurator method configure.
/**
* Configure HTTP Proxy settings of httpcomponents HostConfiguration.
* Proxy settings can be get from axis2.xml, Java proxy settings or can be
* override through property in message context.
* <p/>
* HTTP Proxy setting element format: <parameter name="Proxy">
* <Configuration> <ProxyHost>example.org</ProxyHost>
* <ProxyPort>3128</ProxyPort> <ProxyUser>EXAMPLE/John</ProxyUser>
* <ProxyPassword>password</ProxyPassword> <Configuration> <parameter>
*
* @param messageContext
* in message context for
* @param requestConfig
* the request configuration to fill in
* @param clientContext
* the HTTP client context
* @throws org.apache.axis2.AxisFault
* if Proxy settings are invalid
*/
public static void configure(MessageContext messageContext, RequestConfig.Builder requestConfig, HttpClientContext clientContext) throws AxisFault {
Credentials proxyCredentials = null;
String proxyHost = null;
String nonProxyHosts = null;
Integer proxyPort = -1;
String proxyUser = null;
String proxyPassword = null;
// Getting configuration values from Axis2.xml
Parameter proxySettingsFromAxisConfig = messageContext.getConfigurationContext().getAxisConfiguration().getParameter(HTTPTransportConstants.ATTR_PROXY);
if (proxySettingsFromAxisConfig != null) {
OMElement proxyConfiguration = getProxyConfigurationElement(proxySettingsFromAxisConfig);
proxyHost = getProxyHost(proxyConfiguration);
proxyPort = getProxyPort(proxyConfiguration);
proxyUser = getProxyUser(proxyConfiguration);
proxyPassword = getProxyPassword(proxyConfiguration);
if (proxyUser != null) {
if (proxyPassword == null) {
proxyPassword = "";
}
proxyCredentials = new UsernamePasswordCredentials(proxyUser, proxyPassword);
int proxyUserDomainIndex = proxyUser.indexOf("\\");
if (proxyUserDomainIndex > 0) {
String domain = proxyUser.substring(0, proxyUserDomainIndex);
if (proxyUser.length() > proxyUserDomainIndex + 1) {
String user = proxyUser.substring(proxyUserDomainIndex + 1);
proxyCredentials = new NTCredentials(user, proxyPassword, proxyHost, domain);
}
}
}
}
// If there is runtime proxy settings, these settings will override
// settings from axis2.xml
HttpTransportProperties.ProxyProperties proxyProperties = (HttpTransportProperties.ProxyProperties) messageContext.getProperty(HTTPConstants.PROXY);
if (proxyProperties != null) {
String proxyHostProp = proxyProperties.getProxyHostName();
if (proxyHostProp == null || proxyHostProp.length() <= 0) {
throw new AxisFault("HTTP Proxy host is not available. Host is a MUST parameter");
} else {
proxyHost = proxyHostProp;
}
proxyPort = proxyProperties.getProxyPort();
// Overriding credentials
String userName = proxyProperties.getUserName();
String password = proxyProperties.getPassWord();
String domain = proxyProperties.getDomain();
if (userName != null && password != null && domain != null) {
proxyCredentials = new NTCredentials(userName, password, proxyHost, domain);
} else if (userName != null && domain == null) {
proxyCredentials = new UsernamePasswordCredentials(userName, password);
}
}
// Overriding proxy settings if proxy is available from JVM settings
String host = System.getProperty(HTTPTransportConstants.HTTP_PROXY_HOST);
if (host != null) {
proxyHost = host;
}
String port = System.getProperty(HTTPTransportConstants.HTTP_PROXY_PORT);
if (port != null && !port.isEmpty()) {
proxyPort = Integer.parseInt(port);
}
if (proxyCredentials != null) {
// TODO : Set preemptive authentication, but its not recommended in HC 4
requestConfig.setAuthenticationEnabled(true);
CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
if (credsProvider == null) {
credsProvider = new BasicCredentialsProvider();
clientContext.setCredentialsProvider(credsProvider);
}
credsProvider.setCredentials(AuthScope.ANY, proxyCredentials);
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
requestConfig.setProxy(proxy);
}
}
use of org.apache.http.auth.NTCredentials in project blogwatch by Baeldung.
the class headlessBrowserConfig method openNewWindowWithProxy.
@Override
public void openNewWindowWithProxy(String proxyHost, String proxyServerPort, String proxyUsername, String proxyPassword) {
logger.info("headlessBrowserName-->" + this.headlessBrowserName);
if (GlobalConstants.HEADLESS_BROWSER_HTMLUNIT.equalsIgnoreCase(this.headlessBrowserName)) {
ProxyConfig proxyConfig = new ProxyConfig(proxyHost, Integer.valueOf(proxyServerPort), null);
webDriver = new HtmlUnitDriver(BrowserVersion.getDefault(), true) {
@Override
protected WebClient newWebClient(BrowserVersion version) {
WebClient webClient = super.newWebClient(version);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setProxyConfig(proxyConfig);
webClient.getCredentialsProvider().setCredentials(AuthScope.ANY, new NTCredentials(proxyUsername, proxyPassword, "", ""));
return webClient;
}
};
} else {
if (GlobalConstants.TARGET_ENV_WINDOWS.equalsIgnoreCase(this.getTargetEnv())) {
// TODO
} else {
System.setProperty("webdriver.chrome.driver", Utils.findFile("/chromedriver", this.getTargetEnv()));
}
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--headless");
chromeOptions.addArguments("--no-sandbox");
chromeOptions.addArguments("start-maximized");
chromeOptions.addArguments("disable-infobars");
chromeOptions.addArguments("--disable-extensions");
Proxy proxy = new Proxy();
proxy.setHttpProxy(proxyHost + ":" + proxyServerPort);
proxy.setSslProxy(proxyHost + ":" + proxyServerPort);
chromeOptions.setProxy(proxy);
ChromeDriver chomeDriver = new ChromeDriver(chromeOptions);
chomeDriver.register(UsernameAndPassword.of(proxyUsername, proxyPassword));
webDriver = chomeDriver;
}
}
use of org.apache.http.auth.NTCredentials in project nexus-public by sonatype.
the class ConfigurationCustomizer method apply.
/**
* Apply authentication configuration to plan.
*/
private void apply(final AuthenticationConfiguration authentication, final HttpClientPlan plan, @Nullable final HttpHost proxyHost) {
Credentials credentials;
List<String> authSchemes;
if (authentication instanceof UsernameAuthenticationConfiguration) {
UsernameAuthenticationConfiguration auth = (UsernameAuthenticationConfiguration) authentication;
authSchemes = ImmutableList.of(DIGEST, BASIC);
credentials = new UsernamePasswordCredentials(auth.getUsername(), auth.getPassword());
} else if (authentication instanceof NtlmAuthenticationConfiguration) {
NtlmAuthenticationConfiguration auth = (NtlmAuthenticationConfiguration) authentication;
authSchemes = ImmutableList.of(NTLM, DIGEST, BASIC);
credentials = new NTCredentials(auth.getUsername(), auth.getPassword(), auth.getHost(), auth.getDomain());
} else if (authentication instanceof BearerTokenAuthenticationConfiguration) {
credentials = null;
authSchemes = emptyList();
} else {
throw new IllegalArgumentException("Unsupported authentication configuration: " + authentication);
}
if (credentials != null) {
if (proxyHost != null) {
plan.addCredentials(new AuthScope(proxyHost), credentials);
plan.getRequest().setProxyPreferredAuthSchemes(authSchemes);
} else {
plan.addCredentials(AuthScope.ANY, credentials);
plan.getRequest().setTargetPreferredAuthSchemes(authSchemes);
}
if (authentication.isPreemptive()) {
plan.getClient().addInterceptorFirst(new PreemptiveAuthHttpRequestInterceptor());
}
}
}
use of org.apache.http.auth.NTCredentials in project JavaClasses by genexuslabs.
the class HttpClientJavaLib method execute.
public void execute(String method, String url) {
resetExecParams();
// Funcion genera parte del path en adelante de la URL
url = getURLValid(url).trim();
try {
CookieStore cookiesToSend = null;
if (getHostChanged()) {
if (getSecure() == 1 && getPort() == 80) {
setPort(443);
}
// Seteo de TcpNoDelay
SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(getTcpNoDelay()).build();
this.httpClientBuilder.setDefaultSocketConfig(socketConfig);
cookiesToSend = setAllStoredCookies();
// Cookies Seteo CookieStore
this.httpClientBuilder.setDefaultCookieStore(cookiesToSend);
}
if (getProxyInfoChanged() && !getProxyServerHost().isEmpty() && getProxyServerPort() != 0) {
HttpHost proxy = new HttpHost(getProxyServerHost(), getProxyServerPort());
this.httpClientBuilder.setRoutePlanner(new DefaultProxyRoutePlanner(proxy));
this.reqConfig = RequestConfig.custom().setSocketTimeout(// Se multiplica por 1000 ya que tiene que ir en ms y se recibe en segundos
getTimeout() * 1000).setCookieSpec(CookieSpecs.STANDARD).setProxy(proxy).build();
} else {
this.httpClientBuilder.setRoutePlanner(null);
this.reqConfig = RequestConfig.custom().setConnectTimeout(// Se multiplica por 1000 ya que tiene que ir en ms y se recibe en segundos
getTimeout() * 1000).setCookieSpec(CookieSpecs.STANDARD).build();
}
if (getHostChanged() || getAuthorizationChanged()) {
// Si el host cambio o si se agrego alguna credencial
this.credentialsProvider = new BasicCredentialsProvider();
for (Enumeration en = getBasicAuthorization().elements(); en.hasMoreElements(); ) {
// No se puede hacer la autorizacion del tipo Basic con el BasicCredentialsProvider porque esta funcionando bien en todos los casos
HttpClientPrincipal p = (HttpClientPrincipal) en.nextElement();
addBasicAuthHeader(p.user, p.password, false);
}
for (Enumeration en = getDigestAuthorization().elements(); en.hasMoreElements(); ) {
HttpClientPrincipal p = (HttpClientPrincipal) en.nextElement();
this.credentialsProvider.setCredentials(new AuthScope(getHost(), getPort(), p.realm, AuthSchemes.DIGEST), new UsernamePasswordCredentials(p.user, p.password));
}
for (Enumeration en = getNTLMAuthorization().elements(); en.hasMoreElements(); ) {
HttpClientPrincipal p = (HttpClientPrincipal) en.nextElement();
this.httpClientBuilder.setDefaultAuthSchemeRegistry(RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.NTLM, new NTLMSchemeFactory()).register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build());
try {
credentialsProvider.setCredentials(new AuthScope(getHost(), getPort(), p.realm, AuthSchemes.NTLM), new NTCredentials(p.user, p.password, InetAddress.getLocalHost().getHostName(), getHost()));
} catch (UnknownHostException e) {
credentialsProvider.setCredentials(new AuthScope(getHost(), getPort(), p.realm, AuthSchemes.NTLM), new NTCredentials(p.user, p.password, "localhost", getHost()));
}
}
}
setHostChanged(false);
// Desmarco las flags
setAuthorizationChanged(false);
if (getProxyInfoChanged() || getAuthorizationProxyChanged()) {
// Si el proxyHost cambio o si se agrego alguna credencial para el proxy
if (this.credentialsProvider == null) {
this.credentialsProvider = new BasicCredentialsProvider();
}
for (Enumeration en = getBasicProxyAuthorization().elements(); en.hasMoreElements(); ) {
// No se puede hacer la autorizacion del tipo Basic con el BasicCredentialsProvider porque esta funcionando bien en todos los casos
HttpClientPrincipal p = (HttpClientPrincipal) en.nextElement();
addBasicAuthHeader(p.user, p.password, true);
}
for (Enumeration en = getDigestProxyAuthorization().elements(); en.hasMoreElements(); ) {
HttpClientPrincipal p = (HttpClientPrincipal) en.nextElement();
this.credentialsProvider.setCredentials(new AuthScope(getProxyServerHost(), getProxyServerPort(), p.realm, AuthSchemes.DIGEST), new UsernamePasswordCredentials(p.user, p.password));
}
for (Enumeration en = getNTLMProxyAuthorization().elements(); en.hasMoreElements(); ) {
HttpClientPrincipal p = (HttpClientPrincipal) en.nextElement();
try {
this.credentialsProvider.setCredentials(new AuthScope(getProxyServerHost(), getProxyServerPort(), p.realm, AuthSchemes.NTLM), new NTCredentials(p.user, p.password, InetAddress.getLocalHost().getHostName(), getProxyServerHost()));
} catch (UnknownHostException e) {
this.credentialsProvider.setCredentials(new AuthScope(getProxyServerHost(), getProxyServerPort(), p.realm, AuthSchemes.NTLM), new NTCredentials(p.user, p.password, "localhost", getProxyServerHost()));
}
}
}
// Desmarco las flags
setProxyInfoChanged(false);
setAuthorizationProxyChanged(false);
if (this.credentialsProvider != null) {
// En caso que se haya agregado algun tipo de autenticacion (ya sea para el host destino como para el proxy) se agrega al contexto
httpClientContext = HttpClientContext.create();
httpClientContext.setCredentialsProvider(credentialsProvider);
}
url = setPathUrl(url);
url = CommonUtil.escapeUnsafeChars(url);
if (// Se completa con esquema y host
getSecure() == 1)
// La lib de HttpClient agrega el port
url = url.startsWith("https://") ? url : "https://" + getHost() + (getPort() != 443 ? ":" + getPort() : "") + url;
else
url = url.startsWith("http://") ? url : "http://" + getHost() + ":" + (getPort() == -1 ? "80" : getPort()) + url;
httpClient = this.httpClientBuilder.build();
if (method.equalsIgnoreCase("GET")) {
HttpGetWithBody httpget = new HttpGetWithBody(url.trim());
httpget.setConfig(reqConfig);
Set<String> keys = getheadersToSend().keySet();
for (String header : keys) {
httpget.addHeader(header, getheadersToSend().get(header));
}
httpget.setEntity(new ByteArrayEntity(getData()));
response = httpClient.execute(httpget, httpClientContext);
} else if (method.equalsIgnoreCase("POST")) {
HttpPost httpPost = new HttpPost(url.trim());
httpPost.setConfig(reqConfig);
Set<String> keys = getheadersToSend().keySet();
boolean hasConentType = false;
for (String header : keys) {
httpPost.addHeader(header, getheadersToSend().get(header));
if (header.equalsIgnoreCase("Content-type"))
hasConentType = true;
}
if (// Si no se setea Content-type, se pone uno default
!hasConentType)
httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
ByteArrayEntity dataToSend;
if (!getIsMultipart() && getVariablesToSend().size() > 0)
dataToSend = new ByteArrayEntity(CommonUtil.hashtable2query(getVariablesToSend()).getBytes());
else
dataToSend = new ByteArrayEntity(getData());
httpPost.setEntity(dataToSend);
response = httpClient.execute(httpPost, httpClientContext);
} else if (method.equalsIgnoreCase("PUT")) {
HttpPut httpPut = new HttpPut(url.trim());
httpPut.setConfig(reqConfig);
Set<String> keys = getheadersToSend().keySet();
for (String header : keys) {
httpPut.addHeader(header, getheadersToSend().get(header));
}
httpPut.setEntity(new ByteArrayEntity(getData()));
response = httpClient.execute(httpPut, httpClientContext);
} else if (method.equalsIgnoreCase("DELETE")) {
HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url.trim());
httpDelete.setConfig(reqConfig);
Set<String> keys = getheadersToSend().keySet();
for (String header : keys) {
httpDelete.addHeader(header, getheadersToSend().get(header));
}
if (getVariablesToSend().size() > 0 || getContentToSend().size() > 0)
httpDelete.setEntity(new ByteArrayEntity(getData()));
response = httpClient.execute(httpDelete, httpClientContext);
} else if (method.equalsIgnoreCase("HEAD")) {
HttpHeadWithBody httpHead = new HttpHeadWithBody(url.trim());
httpHead.setConfig(reqConfig);
Set<String> keys = getheadersToSend().keySet();
for (String header : keys) {
httpHead.addHeader(header, getheadersToSend().get(header));
}
httpHead.setEntity(new ByteArrayEntity(getData()));
response = httpClient.execute(httpHead, httpClientContext);
} else if (method.equalsIgnoreCase("CONNECT")) {
HttpConnectMethod httpConnect = new HttpConnectMethod(url.trim());
httpConnect.setConfig(reqConfig);
Set<String> keys = getheadersToSend().keySet();
for (String header : keys) {
httpConnect.addHeader(header, getheadersToSend().get(header));
}
response = httpClient.execute(httpConnect, httpClientContext);
} else if (method.equalsIgnoreCase("OPTIONS")) {
HttpOptionsWithBody httpOptions = new HttpOptionsWithBody(url.trim());
httpOptions.setConfig(reqConfig);
Set<String> keys = getheadersToSend().keySet();
for (String header : keys) {
httpOptions.addHeader(header, getheadersToSend().get(header));
}
httpOptions.setEntity(new ByteArrayEntity(getData()));
response = httpClient.execute(httpOptions, httpClientContext);
} else if (method.equalsIgnoreCase("TRACE")) {
// No lleva payload
HttpTrace httpTrace = new HttpTrace(url.trim());
httpTrace.setConfig(reqConfig);
Set<String> keys = getheadersToSend().keySet();
for (String header : keys) {
httpTrace.addHeader(header, getheadersToSend().get(header));
}
response = httpClient.execute(httpTrace, httpClientContext);
} else if (method.equalsIgnoreCase("PATCH")) {
HttpPatch httpPatch = new HttpPatch(url.trim());
httpPatch.setConfig(reqConfig);
Set<String> keys = getheadersToSend().keySet();
for (String header : keys) {
httpPatch.addHeader(header, getheadersToSend().get(header));
}
ByteArrayEntity dataToSend = new ByteArrayEntity(getData());
httpPatch.setEntity(dataToSend);
response = httpClient.execute(httpPatch, httpClientContext);
}
statusCode = response.getStatusLine().getStatusCode();
reasonLine = response.getStatusLine().getReasonPhrase();
// Se setean las cookies devueltas en la lista de cookies
SetCookieAtr(cookiesToSend);
} catch (IOException e) {
setExceptionsCatch(e);
this.statusCode = 0;
this.reasonLine = "";
} finally {
if (getIsURL()) {
this.setHost(getPrevURLhost());
this.setBaseURL(getPrevURLbaseURL());
this.setPort(getPrevURLport());
this.setSecure(getPrevURLsecure());
setIsURL(false);
}
resetStateAdapted();
}
}
Aggregations