List of usage examples for org.apache.http.auth NTCredentials NTCredentials
public NTCredentials(final String userName, final String password, final String workstation, final String domain)
From source file:org.apache.http.osgi.impl.OSGiCredentialsProvider.java
private static Credentials createNTCredentials(final ProxyConfiguration config) { final String domainAndUsername = config.getUsername(); final String username; final String domain; final int index = domainAndUsername.indexOf("\\"); if (index > -1) { username = domainAndUsername.substring(index + 1); domain = domainAndUsername.substring(0, index); } else {/* ww w. j a v a2s . c o m*/ username = domainAndUsername; domain = null; } return new NTCredentials(username, config.getPassword(), null, domain); }
From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.java
private HttpClient setupClient(URL url, SampleResult res) { Map<HttpClientKey, HttpClient> mapHttpClientPerHttpClientKey = HTTPCLIENTS_CACHE_PER_THREAD_AND_HTTPCLIENTKEY .get();// w ww .j a v a2 s. c o m final String host = url.getHost(); String proxyHost = getProxyHost(); int proxyPort = getProxyPortInt(); String proxyPass = getProxyPass(); String proxyUser = getProxyUser(); // static proxy is the globally define proxy eg command line or properties boolean useStaticProxy = isStaticProxy(host); // dynamic proxy is the proxy defined for this sampler boolean useDynamicProxy = isDynamicProxy(proxyHost, proxyPort); boolean useProxy = useStaticProxy || useDynamicProxy; // if both dynamic and static are used, the dynamic proxy has priority over static if (!useDynamicProxy) { proxyHost = PROXY_HOST; proxyPort = PROXY_PORT; proxyUser = PROXY_USER; proxyPass = PROXY_PASS; } // Lookup key - must agree with all the values used to create the HttpClient. HttpClientKey key = new HttpClientKey(url, useProxy, proxyHost, proxyPort, proxyUser, proxyPass); HttpClient httpClient = null; if (this.testElement.isConcurrentDwn()) { httpClient = (HttpClient) JMeterContextService.getContext().getSamplerContext().get(HTTPCLIENT_TOKEN); } if (httpClient == null) { httpClient = mapHttpClientPerHttpClientKey.get(key); } if (httpClient != null && resetSSLContext && HTTPConstants.PROTOCOL_HTTPS.equalsIgnoreCase(url.getProtocol())) { ((AbstractHttpClient) httpClient).clearRequestInterceptors(); ((AbstractHttpClient) httpClient).clearResponseInterceptors(); httpClient.getConnectionManager().closeIdleConnections(1L, TimeUnit.MICROSECONDS); httpClient = null; JsseSSLManager sslMgr = (JsseSSLManager) SSLManager.getInstance(); sslMgr.resetContext(); resetSSLContext = false; } if (httpClient == null) { // One-time init for this client HttpParams clientParams = new DefaultedHttpParams(new BasicHttpParams(), DEFAULT_HTTP_PARAMS); DnsResolver resolver = this.testElement.getDNSResolver(); if (resolver == null) { resolver = SystemDefaultDnsResolver.INSTANCE; } MeasuringConnectionManager connManager = new MeasuringConnectionManager(createSchemeRegistry(), resolver, TIME_TO_LIVE, VALIDITY_AFTER_INACTIVITY_TIMEOUT); // 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 if (this.testElement.isConcurrentDwn()) { try { int maxConcurrentDownloads = Integer.parseInt(this.testElement.getConcurrentPool()); connManager.setDefaultMaxPerRoute( Math.max(maxConcurrentDownloads, connManager.getDefaultMaxPerRoute())); } catch (NumberFormatException nfe) { // no need to log -> will be done by the sampler } } httpClient = new DefaultHttpClient(connManager, clientParams) { @Override protected HttpRequestRetryHandler createHttpRequestRetryHandler() { return new DefaultHttpRequestRetryHandler(RETRY_COUNT, false); // set retry count } }; if (IDLE_TIMEOUT > 0) { ((AbstractHttpClient) httpClient).setKeepAliveStrategy(IDLE_STRATEGY); } // see https://issues.apache.org/jira/browse/HTTPCORE-397 ((AbstractHttpClient) httpClient).setReuseStrategy(DefaultClientConnectionReuseStrategy.INSTANCE); ((AbstractHttpClient) httpClient).addResponseInterceptor(RESPONSE_CONTENT_ENCODING); ((AbstractHttpClient) httpClient).addResponseInterceptor(METRICS_SAVER); // HACK ((AbstractHttpClient) httpClient).addRequestInterceptor(METRICS_RESETTER); // Override the default schemes as necessary SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry(); if (SLOW_HTTP != null) { schemeRegistry.register(SLOW_HTTP); } // Set up proxy details if (useProxy) { HttpHost proxy = new HttpHost(proxyHost, proxyPort); clientParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (proxyUser.length() > 0) { ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials( new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUser, proxyPass, localHost, PROXY_DOMAIN)); } } // Bug 52126 - we do our own cookie handling clientParams.setParameter(ClientPNames.COOKIE_POLICY, CookieSpecs.IGNORE_COOKIES); if (log.isDebugEnabled()) { log.debug("Created new HttpClient: @" + System.identityHashCode(httpClient) + " " + key.toString()); } mapHttpClientPerHttpClientKey.put(key, httpClient); // save the agent for next time round } else { if (log.isDebugEnabled()) { log.debug("Reusing the HttpClient: @" + System.identityHashCode(httpClient) + " " + key.toString()); } } if (this.testElement.isConcurrentDwn()) { JMeterContextService.getContext().getSamplerContext().put(HTTPCLIENT_TOKEN, httpClient); } // TODO - should this be done when the client is created? // If so, then the details need to be added as part of HttpClientKey setConnectionAuthorization(httpClient, url, getAuthManager(), key); return httpClient; }
From source file:org.datacleaner.user.UserPreferencesImpl.java
@Override public CloseableHttpClient createHttpClient() { final HttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); if (isProxyEnabled()) { // set up HTTP proxy final String proxyHostname = getProxyHostname(); final int proxyPort = getProxyPort(); try {//from w ww . j a v a 2 s . c om final HttpHost proxy = new HttpHost(proxyHostname, proxyPort); requestConfigBuilder.setProxy(proxy); if (isProxyAuthenticationEnabled()) { final AuthScope authScope = new AuthScope(proxyHostname, proxyPort); final String proxyUsername = getProxyUsername(); final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(proxyUsername, getProxyPassword()); credentialsProvider.setCredentials(authScope, credentials); final int backslashIndex = proxyUsername.lastIndexOf('\\'); final String ntUsername; final String ntDomain; if (backslashIndex != -1) { ntUsername = proxyUsername.substring(backslashIndex + 1); ntDomain = proxyUsername.substring(0, backslashIndex); } else { ntUsername = proxyUsername; ntDomain = System.getProperty("datacleaner.proxy.domain"); } String workstation = System.getProperty("datacleaner.proxy.workstation"); if (Strings.isNullOrEmpty(workstation)) { String computername = InetAddress.getLocalHost().getHostName(); workstation = computername; } NTCredentials ntCredentials = new NTCredentials(ntUsername, getProxyPassword(), workstation, ntDomain); AuthScope ntAuthScope = new AuthScope(proxyHostname, proxyPort, AuthScope.ANY_REALM, "ntlm"); credentialsProvider.setCredentials(ntAuthScope, ntCredentials); } } catch (Exception e) { // ignore proxy creation and return http client without it logger.error("Unexpected error occurred while initializing HTTP proxy", e); } } final RequestConfig requestConfig = requestConfigBuilder.build(); final CloseableHttpClient httpClient = HttpClients.custom().useSystemProperties() .setConnectionManager(connectionManager).setDefaultCredentialsProvider(credentialsProvider) .setDefaultRequestConfig(requestConfig).build(); return httpClient; }
From source file:org.eclipse.ecf.provider.filetransfer.httpclient4.HttpClientRetrieveFileTransfer.java
/** * @since 5.0//from w w w . j a v a2 s.c o m */ public static NTCredentials createNTLMCredentials(Proxy p) { if (p == null) { return null; } String un = getNTLMUserName(p); String domain = getNTLMDomainName(p); if (un == null || domain == null) return null; String workstation = null; try { workstation = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { Trace.catching(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_CATCHING, HttpClientRetrieveFileTransfer.class, "createNTLMCredentials", e); //$NON-NLS-1$ } return new NTCredentials(un, p.getPassword(), workstation, domain); }
From source file:org.eobjects.datacleaner.user.UserPreferencesImpl.java
@Override public HttpClient createHttpClient() { final ClientConnectionManager connectionManager = new PoolingClientConnectionManager(); final DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager); if (isProxyEnabled()) { // set up HTTP proxy final String proxyHostname = getProxyHostname(); final int proxyPort = getProxyPort(); try {//from w w w . jav a2s . co m final HttpHost proxy = new HttpHost(proxyHostname, proxyPort); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (isProxyAuthenticationEnabled()) { final AuthScope authScope = new AuthScope(proxyHostname, proxyPort); final String proxyUsername = getProxyUsername(); final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(proxyUsername, getProxyPassword()); httpClient.getCredentialsProvider().setCredentials(authScope, credentials); final int backslashIndex = proxyUsername.lastIndexOf('\\'); final String ntUsername; final String ntDomain; if (backslashIndex != -1) { ntUsername = proxyUsername.substring(backslashIndex + 1); ntDomain = proxyUsername.substring(0, backslashIndex); } else { ntUsername = proxyUsername; ntDomain = System.getProperty("datacleaner.proxy.domain"); } String workstation = System.getProperty("datacleaner.proxy.workstation"); if (Strings.isNullOrEmpty(workstation)) { String computername = InetAddress.getLocalHost().getHostName(); workstation = computername; } NTCredentials ntCredentials = new NTCredentials(ntUsername, getProxyPassword(), workstation, ntDomain); AuthScope ntAuthScope = new AuthScope(proxyHostname, proxyPort, AuthScope.ANY_REALM, "ntlm"); httpClient.getCredentialsProvider().setCredentials(ntAuthScope, ntCredentials); } } catch (Exception e) { // ignore proxy creation and return http client without it logger.error("Unexpected error occurred while initializing HTTP proxy", e); } } return httpClient; }
From source file:org.jets3t.apps.cockpitlite.CockpitLite.java
/** * Implementation method for the CredentialsProvider interface. * <p>/*from w w w .j a va 2 s .com*/ * Based on sample code: * <a href="http://svn.apache.org/viewvc/jakarta/commons/proper/httpclient/trunk/src/examples/InteractiveAuthenticationExample.java?view=markup">InteractiveAuthenticationExample</a> * */ public Credentials getCredentials(AuthScope scope) { if (scope == null || scope.getScheme() == null) { return null; } Credentials credentials = mCredentialProvider.getCredentials(scope); if (credentials != null) { return credentials; } try { if (scope.getScheme().equals("ntlm")) { AuthenticationDialog pwDialog = new AuthenticationDialog(ownerFrame, "Authentication Required", "<html>Host <b>" + scope.getHost() + ":" + scope.getPort() + "</b> requires Windows authentication</html>", true); pwDialog.setVisible(true); if (pwDialog.getUser().length() > 0) { credentials = new NTCredentials(pwDialog.getUser(), pwDialog.getPassword(), scope.getHost(), pwDialog.getDomain()); } pwDialog.dispose(); } else if (scope.getScheme().equals("basic") || scope.getScheme().equals("digest")) { //authscheme instanceof RFC2617Scheme AuthenticationDialog pwDialog = new AuthenticationDialog(ownerFrame, "Authentication Required", "<html><center>Host <b>" + scope.getHost() + ":" + scope.getPort() + "</b>" + " requires authentication for the realm:<br><b>" + scope.getRealm() + "</b></center></html>", false); pwDialog.setVisible(true); if (pwDialog.getUser().length() > 0) { credentials = new UsernamePasswordCredentials(pwDialog.getUser(), pwDialog.getPassword()); } pwDialog.dispose(); } else { throw new InvalidCredentialsException("Unsupported authentication scheme: " + scope.getScheme()); } if (credentials != null) { mCredentialProvider.setCredentials(scope, credentials); } return credentials; } catch (Exception e) { throw new IllegalArgumentException(e.getMessage(), e); } }
From source file:org.mitre.dsmiley.httpproxy.ProxyServlet.java
/** * Called from {@link #init(javax.servlet.ServletConfig)}. HttpClient offers * many opportunities for customization. By default, <a href= * "http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/SystemDefaultHttpClient.html"> * SystemDefaultHttpClient</a> is used if available, otherwise it falls back * to:// w ww . ja v a 2 s. co m * * <pre> * new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams) * </pre> * * SystemDefaultHttpClient uses PoolingClientConnectionManager. In any case, * it should be thread-safe. */ protected HttpClient createHttpClient(HttpParams hcParams) { try { String negotiateURL = getConfigParam("negotiate.url"); String negotiateSPN = getConfigParam("negotiate.spn"); if (negotiateURL != null && negotiateSPN != null) { System.out.println("negotiate url:" + negotiateURL); System.out.println("negotiate spn:" + negotiateSPN); // initialize the Windows security Context to get the negotiate // client token IWindowsSecurityContext clientContext = null; IWindowsCredentialsHandle clientCredentials = null; clientContext = WindowsSecurityContextImpl.getCurrent(SECURITY_PACKAGE, negotiateSPN); clientCredentials = WindowsCredentialsHandleImpl.getCurrent(SECURITY_PACKAGE); clientCredentials.initialize(); String username = WindowsAccountImpl.getCurrentUsername(); System.out.println("credentials for user " + username + " get prepared"); byte[] token = clientContext.getToken(); // encode the token with Base64 to be able to add it to the http // header String clientToken = Base64.encodeBase64String(token); System.out.println("clientToken" + clientToken); // if there is only a negotiate url the rest of the // authorization is based on cookies // so we need to support them. CookieStore cookieStore = new BasicCookieStore(); RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build(); HttpClientContext context = HttpClientContext.create(); proxyContext = context; context.setCookieStore(cookieStore); HttpClient httpClient = HttpClients.custom().disableRedirectHandling() .setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).build(); // first we need to act as a normal browser to get a http 401 // with negotiate header doActAsBrowser = true; HttpGet browserHttpGet = new HttpGet(negotiateURL); addBrowserHeader(browserHttpGet); HttpResponse rep = httpClient.execute(browserHttpGet, context); if (rep.getStatusLine().getStatusCode() == 401) { System.out.println("negotiate requested - sending negotiate client token"); HttpGet negotiateHttpGet = new HttpGet(negotiateURL); addBrowserHeader(negotiateHttpGet); negotiateHttpGet.addHeader("Authorization", "Negotiate " + clientToken); HttpResponse response = httpClient.execute(negotiateHttpGet, context); System.out.println( "http result code of negotiate request:" + response.getStatusLine().getStatusCode()); // now the url needs to be called periodically to keep the // cookie and connection alive String refreshTimeString = getConfigParam("negotiate.refreshtime"); long refreshTime = 1000000; if (refreshTimeString != null) { refreshTime = Long.parseLong(refreshTimeString); } HttpClientRefreshThread thread = new HttpClientRefreshThread(refreshTime, negotiateURL); thread.start(); List<org.apache.http.cookie.Cookie> cookies = context.getCookieStore().getCookies(); cookieString = ""; int size = cookies.size() - 1; for (int i = 0; i < cookies.size(); i++) { cookieString += cookies.get(i).getName(); cookieString += "="; cookieString += cookies.get(i).getValue(); if (i != size) cookieString += "; "; } } else { System.out.println("No negotiate requested"); } } else { if (!WinHttpClients.isWinAuthAvailable()) { System.out.println("Integrated Win auth is not supported!!!"); } else { HttpClientBuilder builder = WinHttpClients.custom(); Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.BASIC, new BasicSchemeFactory()) .register(AuthSchemes.DIGEST, new DigestSchemeFactory()) .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()) .register(AuthSchemes.NTLM, new NTLMSchemeFactory()) .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build(); builder.setDefaultAuthSchemeRegistry(authSchemeRegistry); String username = getConfigParam("user"); String password = getConfigParam("password"); String domain = getConfigParam("domain"); String host = getConfigParam("host"); if (username != null) { NTCredentials cred = new NTCredentials(username, password, host, domain); CredentialsProvider credsProvider = new WindowsCredentialsProvider( new SystemDefaultCredentialsProvider()); credsProvider.setCredentials(AuthScope.ANY, cred); builder.setDefaultCredentialsProvider(credsProvider); } builder.disableCookieManagement(); builder.disableRedirectHandling(); return builder.build(); } // as of HttpComponents v4.2, this class is better since it uses // System // Properties: Class<?> clientClazz = Class.forName("org.apache.http.impl.client.SystemDefaultHttpClient"); Constructor<?> constructor = clientClazz.getConstructor(HttpParams.class); return (HttpClient) constructor.newInstance(hcParams); } } catch (ClassNotFoundException e) { // no problem; use v4.1 below } catch (Exception e) { throw new RuntimeException(e); } // Fallback on using older client: return new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams); }