Example usage for org.apache.http.auth NTCredentials NTCredentials

List of usage examples for org.apache.http.auth NTCredentials NTCredentials

Introduction

In this page you can find the example usage for org.apache.http.auth NTCredentials NTCredentials.

Prototype

public NTCredentials(final String userName, final String password, final String workstation,
        final String domain) 

Source Link

Document

Constructor.

Usage

From source file:org.sonatype.nexus.proxy.storage.remote.httpclient.RemoteStorageContextCustomizer.java

@VisibleForTesting
public void applyAuthenticationConfig(final Builder builder, final RemoteAuthenticationSettings ras,
        final HttpHost proxyHost) {
    if (ras != null) {
        String authScope = "target";
        if (proxyHost != null) {
            authScope = proxyHost.toHostString() + " proxy";
        }/*from  w  w  w  .j a va 2 s  . c o m*/

        final List<String> authorisationPreference = Lists.newArrayListWithExpectedSize(3);
        authorisationPreference.add(AuthSchemes.DIGEST);
        authorisationPreference.add(AuthSchemes.BASIC);
        Credentials credentials = null;
        if (ras instanceof ClientSSLRemoteAuthenticationSettings) {
            throw new IllegalArgumentException("SSL client authentication not yet supported!");
        } else if (ras instanceof NtlmRemoteAuthenticationSettings) {
            final NtlmRemoteAuthenticationSettings nras = (NtlmRemoteAuthenticationSettings) ras;
            // Using NTLM auth, adding it as first in policies
            authorisationPreference.add(0, AuthSchemes.NTLM);
            log.debug("{} authentication setup for NTLM domain '{}'", authScope, nras.getNtlmDomain());
            credentials = new NTCredentials(nras.getUsername(), nras.getPassword(), nras.getNtlmHost(),
                    nras.getNtlmDomain());
        } else if (ras instanceof UsernamePasswordRemoteAuthenticationSettings) {
            final UsernamePasswordRemoteAuthenticationSettings uras = (UsernamePasswordRemoteAuthenticationSettings) ras;
            log.debug("{} authentication setup for remote storage with username '{}'", authScope,
                    uras.getUsername());
            credentials = new UsernamePasswordCredentials(uras.getUsername(), uras.getPassword());
        }

        if (credentials != null) {
            if (proxyHost != null) {
                builder.setCredentials(new AuthScope(proxyHost), credentials);
                builder.getRequestConfigBuilder().setProxyPreferredAuthSchemes(authorisationPreference);
            } else {
                builder.setCredentials(AuthScope.ANY, credentials);
                builder.getRequestConfigBuilder().setTargetPreferredAuthSchemes(authorisationPreference);
            }
        }
    }
}

From source file:org.switchyard.component.http.OutboundHandler.java

/**
 * Start lifecycle./*from w  w w.j a  va2 s .c  o  m*/
 *
 * @throws HttpConsumeException If unable to load or access a HTTP uri
 */
@Override
protected void doStart() throws HttpConsumeException {
    String address = _config.getAddress();
    if (address != null) {
        _baseAddress = address;
    }
    String method = _config.getMethod();
    if (method != null) {
        _httpMethod = method;
    }
    String contentType = _config.getContentType();
    if (contentType != null) {
        _contentType = contentType;
    }
    // Create and configure the HTTP message composer
    _messageComposer = HttpComposition.getMessageComposer(_config);

    if (_config.hasAuthentication()) {
        // Set authentication
        if (_config.isBasicAuth()) {
            _authScope = createAuthScope(_config.getBasicAuthConfig().getHost(),
                    _config.getBasicAuthConfig().getPort(), _config.getBasicAuthConfig().getRealm());
            _credentials = new UsernamePasswordCredentials(_config.getBasicAuthConfig().getUser(),
                    _config.getBasicAuthConfig().getPassword());
            // Create AuthCache instance
            _authCache = new BasicAuthCache();
            _authCache.put(new HttpHost(_authScope.getHost(), _authScope.getPort()),
                    new BasicScheme(ChallengeState.TARGET));
        } else {
            _authScope = createAuthScope(_config.getNtlmAuthConfig().getHost(),
                    _config.getNtlmAuthConfig().getPort(), _config.getNtlmAuthConfig().getRealm());
            _credentials = new NTCredentials(_config.getNtlmAuthConfig().getUser(),
                    _config.getNtlmAuthConfig().getPassword(), "", _config.getNtlmAuthConfig().getDomain());
        }
    }
    if (_config.getProxyConfig() != null) {
        if (_config.getProxyConfig().getPort() != null) {
            _proxyHost = new HttpHost(_config.getProxyConfig().getHost(),
                    Integer.valueOf(_config.getProxyConfig().getPort()).intValue());
        } else {
            _proxyHost = new HttpHost(_config.getProxyConfig().getHost(), -1);
        }
        if (_config.getProxyConfig().getUser() != null) {
            _authScope = createAuthScope(_config.getProxyConfig().getHost(), _config.getProxyConfig().getPort(),
                    null);
            _credentials = new UsernamePasswordCredentials(_config.getProxyConfig().getUser(),
                    _config.getProxyConfig().getPassword());
            if (_authCache == null) {
                _authCache = new BasicAuthCache();
            }
            _authCache.put(_proxyHost, new BasicScheme(ChallengeState.PROXY));
        }
    }
    _timeout = _config.getTimeout();
}

From source file:nl.nn.adapterframework.http.WebServiceNtlmSender.java

public void configure() throws ConfigurationException {
    super.configure();

    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, getTimeout());
    HttpConnectionParams.setSoTimeout(httpParameters, getTimeout());
    httpClient = new DefaultHttpClient(connectionManager, httpParameters);
    httpClient.getAuthSchemes().register("NTLM", new NTLMSchemeFactory());
    CredentialFactory cf = new CredentialFactory(getAuthAlias(), getUserName(), getPassword());
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new NTCredentials(cf.getUsername(), cf.getPassword(), Misc.getHostname(), getAuthDomain()));
    if (StringUtils.isNotEmpty(getProxyHost())) {
        HttpHost proxy = new HttpHost(getProxyHost(), getProxyPort());
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }//w ww  .  j  a  v  a 2 s  .c  o  m
}

From source file:fr.paris.lutece.plugins.mylutece.modules.oauth.authentication.OAuthAuthentication.java

/**
 * Builds a new {@link HttpClient}/*from   w w w  .j a  v a 2  s .  c  o  m*/
 * @return new HttpClient
 */
private HttpClient getHttpClient() {
    DefaultHttpClient client = new DefaultHttpClient();

    String strUserName = AppPropertiesService.getProperty(PROPERTY_PROXY_USERNAME);
    String strPassword = AppPropertiesService.getProperty(PROPERTY_PROXY_PASSWORD);
    String strDomainName = AppPropertiesService.getProperty(PROPERTY_DOMAIN_NAME);

    if (StringUtils.isNotBlank(strUserName) && StringUtils.isNotBlank(strPassword)) {
        // at least Userpasswordcredz
        Credentials creds;

        if (StringUtils.isBlank(strDomainName)) {
            creds = new UsernamePasswordCredentials(strUserName, strPassword);
        } else {
            creds = new NTCredentials(strUserName, strPassword, "", strDomainName);
        }

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, creds);
        client.setCredentialsProvider(credsProvider);

        HttpHost proxy = new HttpHost(AppPropertiesService.getProperty(PROPERTY_PROXY_HOST),
                AppPropertiesService.getPropertyInt(PROPERTY_PROXY_PORT, 8080));
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    return client;
}

From source file:com.baidubce.http.BceHttpClient.java

/**
 * Constructs a new BCE client using the specified client configuration options (ex: max retry attempts, proxy
 * settings, etc), and request metric collector.
 *
 * @param config Configuration options specifying how this client will communicate with BCE (ex: proxy settings,
 *               retry count, etc.)./*from w ww  .  j av  a 2 s . com*/
 *
 * @throws java.lang.IllegalArgumentException If config or signer is null.
 */
public BceHttpClient(BceClientConfiguration config, Signer signer) {
    checkNotNull(config, "config should not be null.");
    checkNotNull(signer, "signer should not be null.");
    this.config = config;
    this.signer = signer;
    this.connectionManager = this.createHttpClientConnectionManager();
    this.httpClient = this.createHttpClient(this.connectionManager);
    IdleConnectionReaper.registerConnectionManager(this.connectionManager);

    this.requestConfigBuilder = RequestConfig.custom();
    this.requestConfigBuilder.setConnectTimeout(config.getConnectionTimeoutInMillis());
    this.requestConfigBuilder.setStaleConnectionCheckEnabled(true);
    if (config.getLocalAddress() != null) {
        this.requestConfigBuilder.setLocalAddress(config.getLocalAddress());
    }

    String proxyHost = config.getProxyHost();
    int proxyPort = config.getProxyPort();
    if (proxyHost != null && proxyPort > 0) {
        this.proxyHttpHost = new HttpHost(proxyHost, proxyPort);
        this.requestConfigBuilder.setProxy(this.proxyHttpHost);

        this.credentialsProvider = new BasicCredentialsProvider();
        String proxyUsername = config.getProxyUsername();
        String proxyPassword = config.getProxyPassword();
        String proxyDomain = config.getProxyDomain();
        String proxyWorkstation = config.getProxyWorkstation();
        if (proxyUsername != null && proxyPassword != null) {
            this.credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }
    }
}

From source file:org.soyatec.windowsazure.internal.util.HttpUtilities.java

private static void addProxyConfig(DefaultHttpClient httpClient) {
    Properties prop = System.getProperties();
    String proxyHost = prop.getProperty("http.proxyHost");
    Integer proxyPort = null;//from   www .  ja  v  a  2s .c  o  m
    if (prop.getProperty("http.proxyPort") != null) {
        proxyPort = Integer.parseInt(prop.getProperty("http.proxyPort"));
    }
    String proxyUserName = prop.getProperty("http.proxyUser");
    String proxyPassword = prop.getProperty("http.proxyPassword");
    String proxyDomain = prop.getProperty("http.proxyDomain");
    if (proxy != null) {
        proxyHost = proxy.getProxyHost();
        proxyPort = proxy.getProxyPort();
        proxyUserName = proxy.getProxyUsername();
        proxyPassword = proxy.getProxyPassword();
        proxyDomain = proxy.getProxyDomainname();
    }

    if (proxyHost != null && proxyPort > 0) {
        Logger.debug(String.format("Using the proxy, proxyHost %s and proxyPort %d", proxyHost, proxyPort));

        HttpHost proxyServer = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyServer);

        if (proxyUserName != null && proxyUserName.trim().length() > 0 && proxyPassword != null
                && proxyPassword.length() > 0) {
            Logger.debug("Proxy Username:" + proxyUserName);
            Logger.debug("Proxy Domain:" + proxyDomain);

            AuthScope authScope = new AuthScope(proxyHost, proxyPort, null);
            NTCredentials credentials = new NTCredentials(proxyUserName, proxyPassword, "", proxyDomain);

            httpClient.getCredentialsProvider().setCredentials(authScope, credentials);

            // Set NTLM authentication
            List<String> authPrefs = new ArrayList<String>();
            authPrefs.add(AuthPolicy.NTLM);
            httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authPrefs);
        }
    }
}

From source file:com.jaeksoft.searchlib.crawler.web.database.CredentialItem.java

public void setUpCredentials(CredentialsProvider credentialProvider) {
    if (StringUtils.isEmpty(username))
        return;/*from  ww  w  .  j a va  2  s . co m*/
    Credentials credentials = null;
    switch (type) {
    case BASIC_DIGEST:
        credentials = new UsernamePasswordCredentials(getUsername(), getPassword());
        break;
    case NTLM:
        credentials = new NTCredentials(getUsername(), getPassword(), getWorkstation(), getDomain());
        break;
    }
    if (credentials != null)
        credentialProvider.setCredentials(AuthScope.ANY, credentials);
}

From source file:com.amazonaws.http.HttpClientFactory.java

/**
 * Creates a new HttpClient object using the specified AWS
 * ClientConfiguration to configure the client.
 *
 * @param config/*from   w w  w .  j a va2 s. co  m*/
 *            Client configuration options (ex: proxy settings, connection
 *            limits, etc).
 *
 * @return The new, configured HttpClient.
 */
public HttpClient createHttpClient(ClientConfiguration config) {
    /* Set HTTP client parameters */
    HttpParams httpClientParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout());
    HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, true);
    HttpConnectionParams.setTcpNoDelay(httpClientParams, true);
    HttpConnectionParams.setSoKeepalive(httpClientParams, config.useTcpKeepAlive());

    int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0];
    int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1];
    if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) {
        HttpConnectionParams.setSocketBufferSize(httpClientParams,
                Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint));
    }
    final SSLContext sslContext = createSSLContext(config);
    SSLSocketFactory sslSocketFactory = config.getApacheHttpClientConfig().getSslSocketFactory();
    if (sslSocketFactory == null) {
        sslSocketFactory = new SdkTLSSocketFactory(sslContext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
    }

    PoolingClientConnectionManager connectionManager = ConnectionManagerFactory
            .createPoolingClientConnManager(config, httpClientParams, sslSocketFactory);

    SdkHttpClient httpClient = new SdkHttpClient(connectionManager, httpClientParams);
    httpClient.setHttpRequestRetryHandler(HttpRequestNoRetryHandler.Singleton);
    httpClient.setRedirectStrategy(new NeverFollowRedirectStrategy());

    if (config.getConnectionMaxIdleMillis() > 0) {
        httpClient
                .setKeepAliveStrategy(new SdkConnectionKeepAliveStrategy(config.getConnectionMaxIdleMillis()));
    }

    if (config.getLocalAddress() != null) {
        ConnRouteParams.setLocalAddress(httpClientParams, config.getLocalAddress());
    }

    Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
    Scheme https = new Scheme("https", 443, sslSocketFactory);
    SchemeRegistry sr = connectionManager.getSchemeRegistry();
    sr.register(http);
    sr.register(https);

    /*
     * 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(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 = config.getProxyHost();
    int proxyPort = config.getProxyPort();
    if (proxyHost != null && proxyPort > 0) {
        AmazonHttpClient.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 = 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));
        }

        // Add a request interceptor that sets up proxy authentication pre-emptively if configured
        if (config.isPreemptiveBasicProxyAuth()) {
            httpClient.addRequestInterceptor(new PreemptiveProxyAuth(proxyHttpHost), 0);
        }
    }

    /* Accept Gzip response if configured */
    if (config.useGzip()) {

        httpClient.addRequestInterceptor(new HttpRequestInterceptor() {

            @Override
            public void process(final HttpRequest request, final HttpContext context)
                    throws HttpException, IOException {
                if (!request.containsHeader("Accept-Encoding")) {
                    request.addHeader("Accept-Encoding", "gzip");
                }
            }

        });

        httpClient.addResponseInterceptor(new HttpResponseInterceptor() {

            @Override
            public void process(final HttpResponse response, final HttpContext context)
                    throws HttpException, IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    Header ceheader = entity.getContentEncoding();
                    if (ceheader != null) {
                        HeaderElement[] codecs = ceheader.getElements();
                        for (int i = 0; i < codecs.length; i++) {
                            if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                                response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                                return;
                            }
                        }
                    }
                }
            }

        });
    }

    return httpClient;
}

From source file:org.nuxeo.wizard.download.PackageDownloader.java

public void setProxy(String proxy, int port, String login, String password, String NTLMHost,
        String NTLMDomain) {/* w ww .ja  va 2s .  com*/
    if (proxy != null) {
        HttpHost proxyHost = new HttpHost(proxy, port);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
        if (login != null) {
            if (NTLMHost != null && !NTLMHost.trim().isEmpty()) {
                NTCredentials ntlmCredentials = new NTCredentials(login, password, NTLMHost, NTLMDomain);
                httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxy, port), ntlmCredentials);
            } else {
                httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxy, port),
                        new UsernamePasswordCredentials(login, password));
            }
        } else {
            httpClient.getCredentialsProvider().clear();
        }
    } else {
        httpClient.getParams().removeParameter(ConnRoutePNames.DEFAULT_PROXY);
        httpClient.getCredentialsProvider().clear();
    }
}