List of usage examples for org.apache.commons.httpclient.auth AuthPolicy NTLM
String NTLM
To view the source code for org.apache.commons.httpclient.auth AuthPolicy NTLM.
Click Source Link
From source file:AlternateAuthenticationExample.java
public static void main(String[] args) throws Exception { HttpClient client = new HttpClient(); client.getState().setCredentials(new AuthScope("myhost", 80, "myrealm"), new UsernamePasswordCredentials("username", "password")); // Suppose the site supports several authetication schemes: NTLM and Basic // Basic authetication is considered inherently insecure. Hence, NTLM authentication // is used per default // This is to make HttpClient pick the Basic authentication scheme over NTLM & Digest List authPrefs = new ArrayList(3); authPrefs.add(AuthPolicy.BASIC);/*from w w w . j av a 2 s . com*/ authPrefs.add(AuthPolicy.NTLM); authPrefs.add(AuthPolicy.DIGEST); client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); GetMethod httpget = new GetMethod("http://myhost/protected/auth-required.html"); try { int status = client.executeMethod(httpget); // print the status and response System.out.println(httpget.getStatusLine()); System.out.println(httpget.getResponseBodyAsString()); } finally { // release any connection resources used by the method httpget.releaseConnection(); } }
From source file:com.liferay.portal.util.HttpImpl.java
public HttpImpl() { // Mimic behavior found in // http://java.sun.com/j2se/1.5.0/docs/guide/net/properties.html if (Validator.isNotNull(_NON_PROXY_HOSTS)) { String nonProxyHostsRegEx = _NON_PROXY_HOSTS; nonProxyHostsRegEx = nonProxyHostsRegEx.replaceAll("\\.", "\\\\."); nonProxyHostsRegEx = nonProxyHostsRegEx.replaceAll("\\*", ".*?"); nonProxyHostsRegEx = nonProxyHostsRegEx.replaceAll("\\|", ")|("); nonProxyHostsRegEx = "(" + nonProxyHostsRegEx + ")"; _nonProxyHostsPattern = Pattern.compile(nonProxyHostsRegEx); }// w w w . j a va 2 s. co m MultiThreadedHttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams httpConnectionManagerParams = httpConnectionManager.getParams(); httpConnectionManagerParams.setConnectionTimeout(_TIMEOUT); httpConnectionManagerParams.setDefaultMaxConnectionsPerHost(new Integer(_MAX_CONNECTIONS_PER_HOST)); httpConnectionManagerParams.setMaxTotalConnections(new Integer(_MAX_TOTAL_CONNECTIONS)); httpConnectionManagerParams.setSoTimeout(_TIMEOUT); _httpClient.setHttpConnectionManager(httpConnectionManager); _proxyHttpClient.setHttpConnectionManager(httpConnectionManager); if (hasProxyConfig() && Validator.isNotNull(_PROXY_USERNAME)) { List<String> authPrefs = new ArrayList<String>(); if (_PROXY_AUTH_TYPE.equals("username-password")) { _proxyCredentials = new UsernamePasswordCredentials(_PROXY_USERNAME, _PROXY_PASSWORD); authPrefs.add(AuthPolicy.BASIC); authPrefs.add(AuthPolicy.DIGEST); authPrefs.add(AuthPolicy.NTLM); } else if (_PROXY_AUTH_TYPE.equals("ntlm")) { _proxyCredentials = new NTCredentials(_PROXY_USERNAME, _PROXY_PASSWORD, _PROXY_NTLM_HOST, _PROXY_NTLM_DOMAIN); authPrefs.add(AuthPolicy.NTLM); authPrefs.add(AuthPolicy.BASIC); authPrefs.add(AuthPolicy.DIGEST); } HttpClientParams httpClientParams = _proxyHttpClient.getParams(); httpClientParams.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); } }
From source file:com.twelve.capital.external.feed.util.HttpImpl.java
public HttpImpl() { // Override the default protocol socket factory because it uses // reflection for JDK 1.4 compatibility, which we do not need. It also // attemps to create a new socket in a different thread so that we // cannot track which class loader initiated the call. Protocol protocol = new Protocol("http", new FastProtocolSocketFactory(), 80); Protocol.registerProtocol("http", protocol); // Mimic behavior found in // http://java.sun.com/j2se/1.5.0/docs/guide/net/properties.html if (Validator.isNotNull(_NON_PROXY_HOSTS)) { String nonProxyHostsRegEx = _NON_PROXY_HOSTS; nonProxyHostsRegEx = nonProxyHostsRegEx.replaceAll("\\.", "\\\\."); nonProxyHostsRegEx = nonProxyHostsRegEx.replaceAll("\\*", ".*?"); nonProxyHostsRegEx = nonProxyHostsRegEx.replaceAll("\\|", ")|("); nonProxyHostsRegEx = "(" + nonProxyHostsRegEx + ")"; _nonProxyHostsPattern = Pattern.compile(nonProxyHostsRegEx); }/* www. j av a 2 s . com*/ MultiThreadedHttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams httpConnectionManagerParams = httpConnectionManager.getParams(); httpConnectionManagerParams.setConnectionTimeout(_TIMEOUT); httpConnectionManagerParams.setDefaultMaxConnectionsPerHost(new Integer(_MAX_CONNECTIONS_PER_HOST)); httpConnectionManagerParams.setMaxTotalConnections(new Integer(_MAX_TOTAL_CONNECTIONS)); httpConnectionManagerParams.setSoTimeout(_TIMEOUT); _httpClient.setHttpConnectionManager(httpConnectionManager); _proxyHttpClient.setHttpConnectionManager(httpConnectionManager); if (!hasProxyConfig() || Validator.isNull(_PROXY_USERNAME)) { return; } List<String> authPrefs = new ArrayList<String>(); if (_PROXY_AUTH_TYPE.equals("username-password")) { _proxyCredentials = new UsernamePasswordCredentials(_PROXY_USERNAME, _PROXY_PASSWORD); authPrefs.add(AuthPolicy.BASIC); authPrefs.add(AuthPolicy.DIGEST); authPrefs.add(AuthPolicy.NTLM); } else if (_PROXY_AUTH_TYPE.equals("ntlm")) { _proxyCredentials = new NTCredentials(_PROXY_USERNAME, _PROXY_PASSWORD, _PROXY_NTLM_HOST, _PROXY_NTLM_DOMAIN); authPrefs.add(AuthPolicy.NTLM); authPrefs.add(AuthPolicy.BASIC); authPrefs.add(AuthPolicy.DIGEST); } HttpClientParams httpClientParams = _proxyHttpClient.getParams(); httpClientParams.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); }
From source file:com.esri.gpt.framework.http.HttpClientRequest.java
/** * Applies authentication and forward proxy settings if required. * @param client the Apache HttpClient/* w w w. ja v a2 s . c om*/ * @param url the target URL * @throws MalformedURLException if the URL is malformed */ private void applyAuthAndProxySettings(HttpClient client, String url) throws MalformedURLException { // initialize the target settings URL targetURL = new URL(url); String targetHost = targetURL.getHost(); int targetPort = targetURL.getPort(); String targetProtocol = targetURL.getProtocol(); if (targetPort == -1) { if (targetProtocol.equalsIgnoreCase("https")) { targetPort = 443; } else { targetPort = 80; } } // TODO: is the host setting required? //HostConfiguration config = client.getHostConfiguration(); //config.setHost(targetHost,targetPort,targetProtocol); // establish authentication credentials if (this.getCredentialProvider() != null) { String username = this.getCredentialProvider().getUsername(); String password = this.getCredentialProvider().getPassword(); if ((username != null) && (username.length() > 0) && (password != null)) { AuthScope scope = new AuthScope(null, -1); UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password); client.getState().setCredentials(scope, creds); // NTLM is based upon username pattern (domain\\username) int ntDomainIdx = username.indexOf("\\"); if (ntDomainIdx > 0) { String left = username.substring(0, ntDomainIdx); String right = username.substring(ntDomainIdx + 1); if ((left.length() > 0) && (right.length() > 0)) { String ntDomain = left; username = right; String ntHost = targetHost; // TODO: should this be the host sending the request? AuthScope ntScope = new AuthScope(null, -1, null, AuthPolicy.NTLM); NTCredentials ntCreds = new NTCredentials(username, password, ntHost, ntDomain); client.getState().setCredentials(ntScope, ntCreds); } } } } // initialize the proxy settings String proxyHost = Val.chkStr((String) System.getProperty(targetProtocol + ".proxyHost")); int proxyPort = Val.chkInt((String) System.getProperty(targetProtocol + ".proxyPort"), -1); String nonProxyHosts = Val.chkStr((String) System.getProperty(targetProtocol + ".nonProxyHosts")); String proxyUser = Val.chkStr((String) System.getProperty(targetProtocol + ".proxyUser")); String proxyPassword = (String) System.getProperty(targetProtocol + ".proxyPassword"); if (proxyPort == -1) { proxyPort = 80; } // check for a non-proxy host match boolean isNonProxyHost = false; if ((proxyHost.length() > 0) && (nonProxyHosts.length() > 0)) { StringTokenizer tokenizer = new StringTokenizer(nonProxyHosts, "|\""); while (tokenizer.hasMoreTokens()) { String nonProxyHost = Val.chkStr(tokenizer.nextToken()); if (nonProxyHost.length() > 0) { if (nonProxyHost.indexOf("*") != -1) { StringBuffer sb = new StringBuffer(); sb.append('^'); for (int i = 0; i < nonProxyHost.length(); i++) { char c = nonProxyHost.charAt(i); switch (c) { case '*': sb.append(".*"); break; case '(': case ')': case '[': case ']': case '$': case '^': case '.': case '{': case '}': case '|': case '\\': case '?': sb.append("\\").append(c); break; default: sb.append(c); break; } } sb.append('$'); nonProxyHost = sb.toString(); } try { if (targetHost.matches(nonProxyHost)) { isNonProxyHost = true; break; } } catch (PatternSyntaxException pse) { // TODO: warn if the pattern syntax is incorrect? //pse.printStackTrace(System.err); } } } } // set the proxy and authentication credentials if required if ((proxyHost.length() > 0) && !isNonProxyHost) { // configure the proxy host and port client.getHostConfiguration().setProxy(proxyHost, proxyPort); // establish proxy-authentication credentials // TODO: lookup gpt.xml proxy-auth String username = proxyUser; String password = proxyPassword; if ((username != null) && (username.length() > 0) && (password != null)) { AuthScope scope = new AuthScope(null, -1); UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password); client.getState().setProxyCredentials(scope, creds); // NTLM is based upon username pattern (domain\\username) int ntDomainIdx = username.indexOf("\\"); if (ntDomainIdx > 0) { String left = username.substring(0, ntDomainIdx); String right = username.substring(ntDomainIdx + 1); if ((left.length() > 0) && (right.length() > 0)) { String ntDomain = left; username = right; String ntHost = proxyHost; // TODO: should this be the host sending the request? AuthScope ntScope = new AuthScope(null, -1, null, AuthPolicy.NTLM); NTCredentials ntCreds = new NTCredentials(username, password, ntHost, ntDomain); client.getState().setProxyCredentials(ntScope, ntCreds); } } } } }
From source file:davmail.http.DavGatewayHttpClientFacade.java
/** * Test if NTLM auth scheme is enabled./*from w ww.ja v a2 s . c om*/ * * @param httpClient HttpClient instance * @return true if NTLM is enabled */ public static boolean hasNTLM(HttpClient httpClient) { Object authPrefs = httpClient.getParams().getParameter(AuthPolicy.AUTH_SCHEME_PRIORITY); return authPrefs == null || (authPrefs instanceof List<?> && ((Collection) authPrefs).contains(AuthPolicy.NTLM)); }
From source file:davmail.http.DavGatewayHttpClientFacade.java
/** * Enable NTLM authentication on http client * * @param httpClient HttpClient instance *///from w ww .j a v a2 s . co m public static void addNTLM(HttpClient httpClient) { // disable preemptive authentication httpClient.getParams().setParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, false); // register the jcifs based NTLMv2 implementation AuthPolicy.registerAuthScheme(AuthPolicy.NTLM, NTLMv2Scheme.class); ArrayList<String> authPrefs = new ArrayList<String>(); authPrefs.add(AuthPolicy.NTLM); authPrefs.add(AuthPolicy.DIGEST); authPrefs.add(AuthPolicy.BASIC); httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); // separate domain from username in credentials AuthScope authScope = new AuthScope(null, -1); NTCredentials credentials = (NTCredentials) httpClient.getState().getCredentials(authScope); String userName = credentials.getUserName(); int backSlashIndex = userName.indexOf('\\'); if (backSlashIndex >= 0) { String domain = userName.substring(0, backSlashIndex); userName = userName.substring(backSlashIndex + 1); credentials = new NTCredentials(userName, credentials.getPassword(), "UNKNOWN", domain); httpClient.getState().setCredentials(authScope, credentials); } // make sure NTLM is always active needNTLM = true; }
From source file:com.cws.esolutions.core.utils.NetworkUtils.java
/** * Creates an HTTP connection to a provided website and returns the data back * to the requestor.//w w w. jav a2 s .c o m * * @param hostName - The fully qualified URL for the host desired. MUST be * prefixed with http/https:// as necessary * @param methodType - GET or POST, depending on what is necessary * @return A object containing the response data * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing */ public static final synchronized Object executeHttpConnection(final URL hostName, final String methodType) throws UtilityException { final String methodName = NetworkUtils.CNAME + "#executeHttpConnection(final URL hostName, final String methodType) throws UtilityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", hostName); DEBUGGER.debug("Value: {}", methodType); } RequestConfig requestConfig = null; CloseableHttpClient httpClient = null; CredentialsProvider credsProvider = null; CloseableHttpResponse httpResponse = null; final HttpClientParams httpParams = new HttpClientParams(); final HTTPConfig httpConfig = appBean.getConfigData().getHttpConfig(); final ProxyConfig proxyConfig = appBean.getConfigData().getProxyConfig(); if (DEBUG) { DEBUGGER.debug("HttpClient: {}", httpClient); DEBUGGER.debug("HttpClientParams: {}", httpParams); DEBUGGER.debug("HTTPConfig: {}", httpConfig); DEBUGGER.debug("ProxyConfig: {}", proxyConfig); } try { final URI requestURI = new URIBuilder().setScheme(hostName.getProtocol()).setHost(hostName.getHost()) .setPort(hostName.getPort()).build(); if (StringUtils.isNotEmpty(httpConfig.getTrustStoreFile())) { System.setProperty("javax.net.ssl.trustStoreType", (StringUtils.isNotEmpty(httpConfig.getTrustStoreType()) ? httpConfig.getTrustStoreType() : "jks")); System.setProperty("javax.net.ssl.trustStore", httpConfig.getTrustStoreFile()); System.setProperty("javax.net.ssl.trustStorePassword", PasswordUtils.decryptText(httpConfig.getTrustStorePass(), httpConfig.getTrustStoreSalt(), secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(), secBean.getConfigData().getSecurityConfig().getIterations(), secBean.getConfigData().getSecurityConfig().getKeyBits(), secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(), secBean.getConfigData().getSecurityConfig().getEncryptionInstance(), appBean.getConfigData().getSystemConfig().getEncoding())); } if (StringUtils.isNotEmpty(httpConfig.getKeyStoreFile())) { System.setProperty("javax.net.ssl.keyStoreType", (StringUtils.isNotEmpty(httpConfig.getKeyStoreType()) ? httpConfig.getKeyStoreType() : "jks")); System.setProperty("javax.net.ssl.keyStore", httpConfig.getKeyStoreFile()); System.setProperty("javax.net.ssl.keyStorePassword", PasswordUtils.decryptText(httpConfig.getKeyStorePass(), httpConfig.getKeyStoreSalt(), secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(), secBean.getConfigData().getSecurityConfig().getIterations(), secBean.getConfigData().getSecurityConfig().getKeyBits(), secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(), secBean.getConfigData().getSecurityConfig().getEncryptionInstance(), appBean.getConfigData().getSystemConfig().getEncoding())); } if (proxyConfig.isProxyServiceRequired()) { if (DEBUG) { DEBUGGER.debug("ProxyConfig: {}", proxyConfig); } if (StringUtils.isEmpty(proxyConfig.getProxyServerName())) { throw new UtilityException( "Configuration states proxy usage is required, but no proxy is configured."); } if (proxyConfig.isProxyAuthRequired()) { List<String> authList = new ArrayList<String>(); authList.add(AuthPolicy.BASIC); authList.add(AuthPolicy.DIGEST); authList.add(AuthPolicy.NTLM); if (DEBUG) { DEBUGGER.debug("authList: {}", authList); } requestConfig = RequestConfig.custom() .setConnectionRequestTimeout( (int) TimeUnit.SECONDS.toMillis(httpConfig.getConnTimeout())) .setConnectTimeout((int) TimeUnit.SECONDS.toMillis(httpConfig.getConnTimeout())) .setContentCompressionEnabled(Boolean.TRUE) .setProxy(new HttpHost(proxyConfig.getProxyServerName(), proxyConfig.getProxyServerPort())) .setProxyPreferredAuthSchemes(authList).build(); if (DEBUG) { DEBUGGER.debug("requestConfig: {}", requestConfig); } String proxyPwd = PasswordUtils.decryptText(proxyConfig.getProxyPassword(), proxyConfig.getProxyPwdSalt(), secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(), secBean.getConfigData().getSecurityConfig().getIterations(), secBean.getConfigData().getSecurityConfig().getKeyBits(), secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(), secBean.getConfigData().getSecurityConfig().getEncryptionInstance(), appBean.getConfigData().getSystemConfig().getEncoding()); if (DEBUG) { DEBUGGER.debug("proxyPwd: {}", proxyPwd); } if (StringUtils.equals(NetworkUtils.PROXY_AUTH_TYPE_BASIC, proxyConfig.getProxyAuthType())) { credsProvider = new SystemDefaultCredentialsProvider(); credsProvider.setCredentials( new AuthScope(proxyConfig.getProxyServerName(), proxyConfig.getProxyServerPort()), new UsernamePasswordCredentials(proxyConfig.getProxyUserId(), proxyPwd)); } else if (StringUtils.equals(NetworkUtils.PROXY_AUTH_TYPE_NTLM, proxyConfig.getProxyAuthType())) { credsProvider = new SystemDefaultCredentialsProvider(); credsProvider.setCredentials( new AuthScope(proxyConfig.getProxyServerName(), proxyConfig.getProxyServerPort()), new NTCredentials(proxyConfig.getProxyUserId(), proxyPwd, InetAddress.getLocalHost().getHostName(), proxyConfig.getProxyAuthDomain())); } if (DEBUG) { DEBUGGER.debug("httpClient: {}", httpClient); } } } synchronized (new Object()) { httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); if (StringUtils.equalsIgnoreCase(methodType, "POST")) { HttpPost httpMethod = new HttpPost(requestURI); httpMethod.setConfig(requestConfig); httpResponse = httpClient.execute(httpMethod); } else { HttpGet httpMethod = new HttpGet(requestURI); httpMethod.setConfig(requestConfig); httpResponse = httpClient.execute(httpMethod); } int responseCode = httpResponse.getStatusLine().getStatusCode(); if (DEBUG) { DEBUGGER.debug("responseCode: {}", responseCode); } if (responseCode != 200) { ERROR_RECORDER.error("HTTP Response Code received NOT 200: " + responseCode); throw new UtilityException("HTTP Response Code received NOT 200: " + responseCode); } return httpResponse.getEntity().toString(); } } catch (ConnectException cx) { throw new UtilityException(cx.getMessage(), cx); } catch (UnknownHostException ux) { throw new UtilityException(ux.getMessage(), ux); } catch (SocketException sx) { throw new UtilityException(sx.getMessage(), sx); } catch (IOException iox) { throw new UtilityException(iox.getMessage(), iox); } catch (URISyntaxException usx) { throw new UtilityException(usx.getMessage(), usx); } finally { if (httpResponse != null) { try { httpResponse.close(); } catch (IOException iox) { } // dont do anything with it } } }
From source file:org.abstracthorizon.proximity.storage.remote.CommonsHttpClientRemotePeer.java
/** * Gets the http client.//from ww w .j a v a 2 s . co m * * @return the http client */ public HttpClient getHttpClient() { if (httpClient == null) { logger.info("Creating CommonsHttpClient instance"); httpRetryHandler = new DefaultHttpMethodRetryHandler(retrievalRetryCount, true); httpClient = new HttpClient(new MultiThreadedHttpConnectionManager()); httpClient.getParams().setConnectionManagerTimeout(getConnectionTimeout()); httpConfiguration = httpClient.getHostConfiguration(); // BASIC and DIGEST auth only if (getUsername() != null) { List authPrefs = new ArrayList(2); authPrefs.add(AuthPolicy.DIGEST); authPrefs.add(AuthPolicy.BASIC); if (getNtlmDomain() != null) { // Using NTLM auth, adding it as first in policies authPrefs.add(0, AuthPolicy.NTLM); logger.info("... authentication setup for NTLM domain {}, username {}", getNtlmDomain(), getUsername()); httpConfiguration.setHost(getNtlmHost()); httpClient.getState().setCredentials(AuthScope.ANY, new NTCredentials(getUsername(), getPassword(), getNtlmHost(), getNtlmDomain())); } else { // Using Username/Pwd auth, will not add NTLM logger.info("... setting authentication setup for remote peer {}, with username {}", getRemoteUrl(), getUsername()); httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(getUsername(), getPassword())); } httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); } if (getProxyHost() != null) { logger.info("... proxy setup with host {}", getProxyHost()); httpConfiguration.setProxy(getProxyHost(), getProxyPort()); if (getProxyUsername() != null) { List authPrefs = new ArrayList(2); authPrefs.add(AuthPolicy.DIGEST); authPrefs.add(AuthPolicy.BASIC); if (getProxyNtlmDomain() != null) { // Using NTLM auth, adding it as first in policies authPrefs.add(0, AuthPolicy.NTLM); if (getNtlmHost() != null) { logger.warn("... CommonsHttpClient is unable to use NTLM auth scheme\n" + " for BOTH server side and proxy side authentication!\n" + " You MUST reconfigure server side auth and use BASIC/DIGEST scheme\n" + " if you have to use NTLM proxy, since otherwise it will not work!\n" + " *** SERVER SIDE AUTH OVERRIDDEN"); } logger.info("... proxy authentication setup for NTLM domain {}, username {}", getProxyNtlmDomain(), getProxyUsername()); httpConfiguration.setHost(getProxyNtlmHost()); httpClient.getState().setProxyCredentials(AuthScope.ANY, new NTCredentials( getProxyUsername(), getProxyPassword(), getProxyNtlmHost(), getProxyNtlmDomain())); } else { // Using Username/Pwd auth, will not add NTLM logger.info("... proxy authentication setup for http proxy {}, username {}", getProxyHost(), getProxyUsername()); httpClient.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(getProxyUsername(), getProxyPassword())); } httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); } } } return httpClient; }
From source file:org.apache.axis2.transport.http.AbstractHTTPSender.java
protected void setAuthenticationInfo(HttpClient agent, MessageContext msgCtx, HostConfiguration config) throws AxisFault { HttpTransportProperties.Authenticator authenticator; Object obj = msgCtx.getProperty(HTTPConstants.AUTHENTICATE); if (obj != null) { if (obj instanceof HttpTransportProperties.Authenticator) { authenticator = (HttpTransportProperties.Authenticator) obj; String username = authenticator.getUsername(); String password = authenticator.getPassword(); String host = authenticator.getHost(); String domain = authenticator.getDomain(); int port = authenticator.getPort(); String realm = authenticator.getRealm(); /* If retrying is available set it first */ isAllowedRetry = authenticator.isAllowedRetry(); Credentials creds;/*from w w w . ja v a 2 s . co m*/ HttpState tmpHttpState = null; HttpState httpState = (HttpState) msgCtx.getProperty(HTTPConstants.CACHED_HTTP_STATE); if (httpState != null) { tmpHttpState = httpState; } else { tmpHttpState = agent.getState(); } agent.getParams().setAuthenticationPreemptive(authenticator.getPreemptiveAuthentication()); if (host != null) { if (domain != null) { /*Credentials for NTLM Authentication*/ creds = new NTCredentials(username, password, host, domain); } else { /*Credentials for Digest and Basic Authentication*/ creds = new UsernamePasswordCredentials(username, password); } tmpHttpState.setCredentials(new AuthScope(host, port, realm), creds); } else { if (domain != null) { /*Credentials for NTLM Authentication when host is ANY_HOST*/ creds = new NTCredentials(username, password, AuthScope.ANY_HOST, domain); tmpHttpState.setCredentials(new AuthScope(AuthScope.ANY_HOST, port, realm), creds); } else { /*Credentials only for Digest and Basic Authentication*/ creds = new UsernamePasswordCredentials(username, password); tmpHttpState.setCredentials(new AuthScope(AuthScope.ANY), creds); } } /* Customizing the priority Order */ List schemes = authenticator.getAuthSchemes(); if (schemes != null && schemes.size() > 0) { List authPrefs = new ArrayList(3); for (int i = 0; i < schemes.size(); i++) { if (schemes.get(i) instanceof AuthPolicy) { authPrefs.add(schemes.get(i)); continue; } String scheme = (String) schemes.get(i); if (HttpTransportProperties.Authenticator.BASIC.equals(scheme)) { authPrefs.add(AuthPolicy.BASIC); } else if (HttpTransportProperties.Authenticator.NTLM.equals(scheme)) { authPrefs.add(AuthPolicy.NTLM); } else if (HttpTransportProperties.Authenticator.DIGEST.equals(scheme)) { authPrefs.add(AuthPolicy.DIGEST); } } agent.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); } } else { throw new AxisFault("HttpTransportProperties.Authenticator class cast exception"); } } }
From source file:org.apache.ivy.util.url.HttpClientHandler.java
private HttpClient getClient() { if (httpClient == null) { final MultiThreadedHttpConnectionManager connManager = new MultiThreadedHttpConnectionManager(); httpClient = new HttpClient(connManager); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { connManager.shutdown();//from w w w . j a v a 2 s .c o m } })); List authPrefs = new ArrayList(3); authPrefs.add(AuthPolicy.DIGEST); authPrefs.add(AuthPolicy.BASIC); authPrefs.add(AuthPolicy.NTLM); // put it at the end to give less priority (IVY-213) httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); if (useProxy()) { httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort); if (useProxyAuthentication()) { httpClient.getState().setProxyCredentials( new AuthScope(proxyHost, proxyPort, AuthScope.ANY_REALM), createCredentials(proxyUserName, proxyPasswd)); } } // user-agent httpClient.getParams().setParameter(HttpMethodParams.USER_AGENT, getUserAgent()); // authentication httpClient.getParams().setParameter(CredentialsProvider.PROVIDER, new IvyCredentialsProvider()); } return httpClient; }