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:com.aliyun.oss.common.comm.DefaultServiceClient.java
public DefaultServiceClient(ClientConfiguration config) { super(config); this.connectionManager = createHttpClientConnectionManager(); this.httpClient = createHttpClient(this.connectionManager); RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); requestConfigBuilder.setConnectTimeout(config.getConnectionTimeout()); requestConfigBuilder.setSocketTimeout(config.getSocketTimeout()); requestConfigBuilder.setConnectionRequestTimeout(config.getConnectionRequestTimeout()); String proxyHost = config.getProxyHost(); int proxyPort = config.getProxyPort(); if (proxyHost != null && proxyPort > 0) { this.proxyHttpHost = new HttpHost(proxyHost, proxyPort); requestConfigBuilder.setProxy(proxyHttpHost); String proxyUsername = config.getProxyUsername(); String proxyPassword = config.getProxyPassword(); String proxyDomain = config.getProxyDomain(); String proxyWorkstation = config.getProxyWorkstation(); if (proxyUsername != null && proxyPassword != null) { this.credentialsProvider = new BasicCredentialsProvider(); this.credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain)); this.authCache = new BasicAuthCache(); authCache.put(this.proxyHttpHost, new BasicScheme()); }// w w w.j a v a 2 s . c o m } this.requestConfig = requestConfigBuilder.build(); }
From source file:microsoft.exchange.webservices.data.HttpClientWebRequest.java
/** * Prepare connection//from w w w . j av a 2 s . c om * * @throws microsoft.exchange.webservices.data.EWSHttpException the eWS http exception */ @Override public void prepareConnection() throws EWSHttpException { try { HttpClientBuilder builder = HttpClients.custom(); builder.setConnectionManager(this.httpClientConnMng); //create the cookie store if (cookieStore == null) { cookieStore = new BasicCookieStore(); } builder.setDefaultCookieStore(cookieStore); if (getProxy() != null) { HttpHost proxy = new HttpHost(getProxy().getHost(), getProxy().getPort()); builder.setProxy(proxy); if (HttpProxyCredentials.isProxySet()) { NTCredentials cred = new NTCredentials(HttpProxyCredentials.getUserName(), HttpProxyCredentials.getPassword(), "", HttpProxyCredentials.getDomain()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxy), cred); builder.setDefaultCredentialsProvider(credsProvider); } } if (getUserName() != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new NTCredentials(getUserName(), getPassword(), "", getDomain())); builder.setDefaultCredentialsProvider(credsProvider); } //fix socket config SocketConfig sc = SocketConfig.custom().setSoTimeout(getTimeout()).build(); builder.setDefaultSocketConfig(sc); RequestConfig.Builder rcBuilder = RequestConfig.custom(); rcBuilder.setAuthenticationEnabled(true); rcBuilder.setConnectionRequestTimeout(getTimeout()); rcBuilder.setConnectTimeout(getTimeout()); rcBuilder.setRedirectsEnabled(isAllowAutoRedirect()); rcBuilder.setSocketTimeout(getTimeout()); // fix issue #144 + #160: if we used NTCredentials from above: these are NT credentials if (getUserName() != null) { ArrayList<String> authPrefs = new ArrayList<String>(); authPrefs.add(AuthSchemes.NTLM); rcBuilder.setTargetPreferredAuthSchemes(authPrefs); } // builder.setDefaultRequestConfig(rcBuilder.build()); httpPostReq = new HttpPost(getUrl().toString()); httpPostReq.addHeader("Content-type", getContentType()); //httpPostReq.setDoAuthentication(true); httpPostReq.addHeader("User-Agent", getUserAgent()); httpPostReq.addHeader("Accept", getAccept()); httpPostReq.addHeader("Keep-Alive", "300"); httpPostReq.addHeader("Connection", "Keep-Alive"); if (isAcceptGzipEncoding()) { httpPostReq.addHeader("Accept-Encoding", "gzip,deflate"); } if (getHeaders().size() > 0) { for (Map.Entry<String, String> httpHeader : getHeaders().entrySet()) { httpPostReq.addHeader(httpHeader.getKey(), httpHeader.getValue()); } } //create the client client = builder.build(); } catch (Exception er) { er.printStackTrace(); } }
From source file:ch.admin.hermes.etl.load.SharePoint2010RESTClient.java
/** * @throws IOException/*ww w. j av a 2s. c o m*/ */ private void init(String remote, String user, String pass) throws IOException { this.remote = (remote != null) ? remote : this.remote; this.user = (user != null) ? user : this.user; this.pass = (pass != null) ? pass : this.pass; client = getHttpClient(); // localhost und domain nicht setzen, gibt Probleme mit https:// NTCredentials creds = new NTCredentials(this.user, this.pass, "", ""); client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds); List<String> authpref = new ArrayList<String>(); authpref.add(AuthPolicy.NTLM); client.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref); }
From source file:net.siegmar.japtproxy.fetcher.HttpClientConfigurer.java
protected Credentials buildNTCredentials(final String userPart, final String password) throws InitializationException { final String domain = StringUtils.substringBefore(userPart, "\\"); final String username = StringUtils.substringAfter(userPart, "\\"); return new NTCredentials(username, password, getLocalHostName(), domain); }
From source file:com.amazon.s3.http.HttpClientFactory.java
/** * Creates a new HttpClient object using the specified AWS * ClientConfiguration to configure the client. */* w w w . j a v a2 s . c om*/ * @param config * Client configuration options (ex: proxy settings, connection * limits, etc). * * @return The new, configured HttpClient. */ public HttpClient createHttpClient(ClientConfiguration config) { /* Form User-Agent information */ String userAgent = config.getUserAgent(); if (!(userAgent.equals(ClientConfiguration.DEFAULT_USER_AGENT))) { userAgent += ", " + ClientConfiguration.DEFAULT_USER_AGENT; } /* Set HTTP client parameters */ HttpParams httpClientParams = new BasicHttpParams(); HttpClientParams.setRedirecting(httpClientParams, false); HttpProtocolParams.setUserAgent(httpClientParams, userAgent); HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout()); HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout()); HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, false); HttpConnectionParams.setTcpNoDelay(httpClientParams, true); int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0]; int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1]; if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) { HttpConnectionParams.setSocketBufferSize(httpClientParams, Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint)); } /* Set connection manager */ ThreadSafeClientConnManager connectionManager = ConnectionManagerFactory .createThreadSafeClientConnManager(config, httpClientParams); DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpClientParams); /* Set proxy if configured */ String proxyHost = config.getProxyHost(); int proxyPort = config.getProxyPort(); if (proxyHost != null && proxyPort > 0) { Log.i(TAG, "Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort); HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost); String proxyUsername = config.getProxyUsername(); String proxyPassword = config.getProxyPassword(); String proxyDomain = config.getProxyDomain(); String proxyWorkstation = config.getProxyWorkstation(); if (proxyUsername != null && proxyPassword != null) { httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain)); } } return httpClient; }
From source file:org.ops4j.pax.url.mvn.internal.wagon.ConfigurableHttpWagon.java
@Override protected CloseableHttpResponse execute(HttpUriRequest httpMethod) throws HttpException, IOException { setHeaders(httpMethod);//from w w w.j a va 2 s .c om String userAgent = getUserAgent(httpMethod); if (userAgent != null) { httpMethod.setHeader(HTTP.USER_AGENT, userAgent); } RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); // WAGON-273: default the cookie-policy to browser compatible requestConfigBuilder.setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY); Repository repo = getRepository(); ProxyInfo proxyInfo = getProxyInfo(repo.getProtocol(), repo.getHost()); if (proxyInfo != null) { HttpHost proxy = new HttpHost(proxyInfo.getHost(), proxyInfo.getPort()); requestConfigBuilder.setProxy(proxy); } HttpMethodConfiguration config = getHttpConfiguration() == null ? null : getHttpConfiguration().getMethodConfiguration(httpMethod); if (config != null) { copyConfig(config, requestConfigBuilder); } else { requestConfigBuilder.setSocketTimeout(getReadTimeout()); requestConfigBuilder.setConnectTimeout(getTimeout()); } getLocalContext().setRequestConfig(requestConfigBuilder.build()); if (config != null && config.isUsePreemptive()) { HttpHost targetHost = new HttpHost(repo.getHost(), repo.getPort(), repo.getProtocol()); AuthScope targetScope = getBasicAuthScope().getScope(targetHost); if (getCredentialsProvider().getCredentials(targetScope) != null) { BasicScheme targetAuth = new BasicScheme(); targetAuth.processChallenge(new BasicHeader(AUTH.WWW_AUTH, "BASIC preemptive")); getAuthCache().put(targetHost, targetAuth); } } if (proxyInfo != null) { if (proxyInfo.getHost() != null) { HttpHost proxyHost = new HttpHost(proxyInfo.getHost(), proxyInfo.getPort()); AuthScope proxyScope = getProxyBasicAuthScope().getScope(proxyHost); String proxyUsername = proxyInfo.getUserName(); String proxyPassword = proxyInfo.getPassword(); String proxyNtlmHost = proxyInfo.getNtlmHost(); String proxyNtlmDomain = proxyInfo.getNtlmDomain(); if (proxyUsername != null && proxyPassword != null) { Credentials creds; if (proxyNtlmHost != null || proxyNtlmDomain != null) { creds = new NTCredentials(proxyUsername, proxyPassword, proxyNtlmHost, proxyNtlmDomain); } else { creds = new UsernamePasswordCredentials(proxyUsername, proxyPassword); } getCredentialsProvider().setCredentials(proxyScope, creds); BasicScheme proxyAuth = new BasicScheme(); proxyAuth.processChallenge(new BasicHeader(AUTH.PROXY_AUTH, "BASIC preemptive")); getAuthCache().put(proxyHost, proxyAuth); } } } return client.execute(httpMethod, getLocalContext()); }
From source file:ch.admin.hermes.etl.load.SharePointRESTClient.java
/** * @throws IOException/*from w w w . j a v a2 s. c o m*/ */ private void init(String remote, String user, String pass) throws IOException { this.remote = (remote != null) ? remote : this.remote; this.user = (user != null) ? user : this.user; this.pass = (pass != null) ? pass : this.pass; client = getHttpClient(); // localhost und domain nicht setzen, gibt Probleme mit https:// NTCredentials creds = new NTCredentials(this.user, this.pass, "", ""); client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds); List<String> authpref = new ArrayList<String>(); authpref.add(AuthPolicy.NTLM); client.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref); // FormDigestValue holen try { js = factory.getEngineByName("JavaScript"); js.eval("function getId(rc) { print(rc); return(rc.d.GetContextWebInformation.FormDigestValue); }"); String out = post("/_api/contextinfo", null); js.eval("var rc = " + out + ";"); Object rc = js.get("rc"); xRequestDigest = (String) ((Invocable) js).invokeFunction("getId", rc); } catch (NoSuchMethodException e) { throw new IOException(e); } catch (ScriptException e) { throw new IOException(e); } }
From source file:org.sonatype.nexus.error.reporting.NexusPRConnector.java
private static void configureAuthentication(final DefaultHttpClient httpClient, final String proxyHost, final int proxyPort, final RemoteAuthenticationSettings ras) { if (ras != null) { List<String> authorisationPreference = new ArrayList<String>(2); authorisationPreference.add(AuthPolicy.DIGEST); authorisationPreference.add(AuthPolicy.BASIC); Credentials credentials = null;//from ww w . j a v a 2s.c om if (ras instanceof NtlmRemoteAuthenticationSettings) { final NtlmRemoteAuthenticationSettings nras = (NtlmRemoteAuthenticationSettings) ras; // Using NTLM auth, adding it as first in policies authorisationPreference.add(0, AuthPolicy.NTLM); credentials = new NTCredentials(nras.getUsername(), nras.getPassword(), nras.getNtlmHost(), nras.getNtlmDomain()); } else if (ras instanceof UsernamePasswordRemoteAuthenticationSettings) { UsernamePasswordRemoteAuthenticationSettings uras = (UsernamePasswordRemoteAuthenticationSettings) ras; credentials = new UsernamePasswordCredentials(uras.getUsername(), uras.getPassword()); } if (credentials != null) { httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort), credentials); } httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authorisationPreference); } }
From source file:com.jaspersoft.ireport.jasperserver.ws.http.JSSCommonsHTTPSender.java
/** * invoke creates a socket connection, sends the request SOAP message and * then reads the response SOAP message back from the SOAP server * * @param msgContext//from w ww.j a va2 s. c o m * the messsage context * * @throws AxisFault */ public void invoke(final MessageContext msgContext) throws AxisFault { if (log.isDebugEnabled()) log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke")); Request req = null; Response response = null; try { if (exec == null) { targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL)); String userID = msgContext.getUsername(); String passwd = msgContext.getPassword(); // if UserID is not part of the context, but is in the URL, use // the one in the URL. if ((userID == null) && (targetURL.getUserInfo() != null)) { String info = targetURL.getUserInfo(); int sep = info.indexOf(':'); if ((sep >= 0) && (sep + 1 < info.length())) { userID = info.substring(0, sep); passwd = info.substring(sep + 1); } else userID = info; } Credentials cred = new UsernamePasswordCredentials(userID, passwd); if (userID != null) { // if the username is in the form "user\domain" // then use NTCredentials instead. int domainIndex = userID.indexOf("\\"); if (domainIndex > 0) { String domain = userID.substring(0, domainIndex); if (userID.length() > domainIndex + 1) { String user = userID.substring(domainIndex + 1); cred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain); } } } HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy() { public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { URI uri = getLocationURI(request, response, context); String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) return new HttpHead(uri); else if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) { HttpPost httpPost = new HttpPost(uri); httpPost.addHeader(request.getFirstHeader("Authorization")); httpPost.addHeader(request.getFirstHeader("SOAPAction")); httpPost.addHeader(request.getFirstHeader("Content-Type")); httpPost.addHeader(request.getFirstHeader("User-Agent")); httpPost.addHeader(request.getFirstHeader("SOAPAction")); if (request instanceof HttpEntityEnclosingRequest) httpPost.setEntity(((HttpEntityEnclosingRequest) request).getEntity()); return httpPost; } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) { return new HttpGet(uri); } else { throw new IllegalStateException( "Redirect called on un-redirectable http method: " + method); } } }).build(); exec = Executor.newInstance(httpClient); HttpHost host = new HttpHost(targetURL.getHost(), targetURL.getPort(), targetURL.getProtocol()); exec.auth(host, cred); exec.authPreemptive(host); HttpUtils.setupProxy(exec, targetURL.toURI()); } boolean posting = true; // If we're SOAP 1.2, allow the web method to be set from the // MessageContext. if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD); if (webMethod != null) posting = webMethod.equals(HTTPConstants.HEADER_POST); } HttpHost proxy = HttpUtils.getUnauthProxy(exec, targetURL.toURI()); if (posting) { req = Request.Post(targetURL.toString()); if (proxy != null) req.viaProxy(proxy); Message reqMessage = msgContext.getRequestMessage(); addContextInfo(req, msgContext, targetURL); Iterator<?> it = reqMessage.getAttachments(); if (it.hasNext()) { ByteArrayOutputStream bos = null; try { bos = new ByteArrayOutputStream(); reqMessage.writeTo(bos); req.body(new ByteArrayEntity(bos.toByteArray())); } finally { FileUtils.closeStream(bos); } } else req.body(new StringEntity(reqMessage.getSOAPPartAsString())); } else { req = Request.Get(targetURL.toString()); if (proxy != null) req.viaProxy(proxy); addContextInfo(req, msgContext, targetURL); } response = exec.execute(req); response.handleResponse(new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws IOException { HttpEntity en = response.getEntity(); InputStream in = null; try { StatusLine statusLine = response.getStatusLine(); int returnCode = statusLine.getStatusCode(); String contentType = en.getContentType().getValue(); in = new BufferedHttpEntity(en).getContent(); // String str = IOUtils.toString(in); if (returnCode > 199 && returnCode < 300) { // SOAP return is OK - so fall through } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { // For now, if we're SOAP 1.2, fall // through, since the range of // valid result codes is much greater } else if (contentType != null && !contentType.equals("text/html") && ((returnCode > 499) && (returnCode < 600))) { // SOAP Fault should be in here - so // fall through } else { String statusMessage = statusLine.getReasonPhrase(); AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null); fault.setFaultDetailString( Messages.getMessage("return01", "" + returnCode, IOUtils.toString(in))); fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode)); throw fault; } Header contentEncoding = response.getFirstHeader(HTTPConstants.HEADER_CONTENT_ENCODING); if (contentEncoding != null) { if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) in = new GZIPInputStream(in); else { AxisFault fault = new AxisFault("HTTP", "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null, null); throw fault; } } // Transfer HTTP headers of HTTP message // to MIME headers of SOAP // message MimeHeaders mh = new MimeHeaders(); for (Header h : response.getAllHeaders()) mh.addHeader(h.getName(), h.getValue()); Message outMsg = new Message(in, false, mh); outMsg.setMessageType(Message.RESPONSE); msgContext.setResponseMessage(outMsg); if (log.isDebugEnabled()) { log.debug("\n" + Messages.getMessage("xmlRecd00")); log.debug("-----------------------------------------------"); log.debug(outMsg.getSOAPPartAsString()); } } finally { FileUtils.closeStream(in); } return ""; } }); } catch (Exception e) { e.printStackTrace(); log.debug(e); throw AxisFault.makeFault(e); } if (log.isDebugEnabled()) log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke")); }
From source file:com.emc.vipr.services.s3.ViPRS3HttpClient.java
public ViPRS3HttpClient(ViPRS3Config viprConfig) { super(viprConfig.getClientConfiguration(), new SmartHttpClient(viprConfig.toSmartClientConfig()), null); ClientConfiguration azConfig = viprConfig.getClientConfiguration(); HttpParams httpClientParams = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(httpClientParams, azConfig.getConnectionTimeout()); HttpConnectionParams.setSoTimeout(httpClientParams, azConfig.getSocketTimeout()); HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, true); HttpConnectionParams.setTcpNoDelay(httpClientParams, true); int socketSendBufferSizeHint = azConfig.getSocketBufferSizeHints()[0]; int socketReceiveBufferSizeHint = azConfig.getSocketBufferSizeHints()[1]; if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) { HttpConnectionParams.setSocketBufferSize(httpClientParams, Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint)); }//www. j a v a 2s. c o m ClientConnectionManager connectionManager = httpClient.getConnectionManager(); ((SmartHttpClient) httpClient).setRedirectStrategy(new LocationHeaderNotRequiredRedirectStrategy()); try { Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory()); SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(), SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); Scheme https = new Scheme("https", 443, sf); SchemeRegistry sr = connectionManager.getSchemeRegistry(); sr.register(http); sr.register(https); } catch (NoSuchAlgorithmException e) { throw new AmazonClientException("Unable to access default SSL context", e); } /* * If SSL cert checking for endpoints has been explicitly disabled, * register a new scheme for HTTPS that won't cause self-signed certs to * error out. */ if (System.getProperty(SDKGlobalConfiguration.DISABLE_CERT_CHECKING_SYSTEM_PROPERTY) != null) { Scheme sch = new Scheme("https", 443, new TrustingSocketFactory()); httpClient.getConnectionManager().getSchemeRegistry().register(sch); } /* Set proxy if configured */ String proxyHost = azConfig.getProxyHost(); int proxyPort = azConfig.getProxyPort(); if (proxyHost != null && proxyPort > 0) { log.info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort); HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost); String proxyUsername = azConfig.getProxyUsername(); String proxyPassword = azConfig.getProxyPassword(); String proxyDomain = azConfig.getProxyDomain(); String proxyWorkstation = azConfig.getProxyWorkstation(); if (proxyUsername != null && proxyPassword != null) { ((SmartHttpClient) httpClient).getCredentialsProvider().setCredentials( new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain)); } // Add a request interceptor that sets up proxy authentication pre-emptively if configured if (azConfig.isPreemptiveBasicProxyAuth()) { ((SmartHttpClient) httpClient).addRequestInterceptor(new PreemptiveProxyAuth(proxyHttpHost), 0); } } }