Example usage for org.apache.http.client.config AuthSchemes NTLM

List of usage examples for org.apache.http.client.config AuthSchemes NTLM

Introduction

In this page you can find the example usage for org.apache.http.client.config AuthSchemes NTLM.

Prototype

String NTLM

To view the source code for org.apache.http.client.config AuthSchemes NTLM.

Click Source Link

Document

The NTLM scheme is a proprietary Microsoft Windows Authentication protocol (considered to be the most secure among currently supported authentication schemes).

Usage

From source file:microsoft.exchange.webservices.data.core.request.HttpClientWebRequest.java

/**
 * Prepares the request by setting appropriate headers, authentication, timeouts, etc.
 */// w w w  .j  a v a 2 s .c  om
@Override
public void prepareConnection() {
    httpPost = new HttpPost(getUrl().toString());

    // Populate headers.
    httpPost.addHeader("Content-type", getContentType());
    httpPost.addHeader("User-Agent", getUserAgent());
    httpPost.addHeader("Accept", getAccept());
    httpPost.addHeader("Keep-Alive", "300");
    httpPost.addHeader("Connection", "Keep-Alive");

    if (isAcceptGzipEncoding()) {
        httpPost.addHeader("Accept-Encoding", "gzip,deflate");
    }

    if (getHeaders() != null) {
        for (Map.Entry<String, String> httpHeader : getHeaders().entrySet()) {
            httpPost.addHeader(httpHeader.getKey(), httpHeader.getValue());
        }
    }

    // Build request configuration.
    // Disable Kerberos in the preferred auth schemes - EWS should usually allow NTLM or Basic auth
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setAuthenticationEnabled(true)
            .setConnectionRequestTimeout(getTimeout()).setConnectTimeout(getTimeout())
            .setRedirectsEnabled(isAllowAutoRedirect()).setSocketTimeout(getTimeout())
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.BASIC))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.BASIC));

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    // Add proxy credential if necessary.
    WebProxy proxy = getProxy();
    if (proxy != null) {
        HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort());
        requestConfigBuilder.setProxy(proxyHost);

        if (proxy.hasCredentials()) {
            NTCredentials proxyCredentials = new NTCredentials(proxy.getCredentials().getUsername(),
                    proxy.getCredentials().getPassword(), "", proxy.getCredentials().getDomain());

            credentialsProvider.setCredentials(new AuthScope(proxyHost), proxyCredentials);
        }
    }

    // Add web service credential if necessary.
    if (isAllowAuthentication() && getUsername() != null) {
        NTCredentials webServiceCredentials = new NTCredentials(getUsername(), getPassword(), "", getDomain());
        credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY), webServiceCredentials);
    }

    httpContext.setCredentialsProvider(credentialsProvider);

    httpPost.setConfig(requestConfigBuilder.build());
}

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";
        }/* ww 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:microsoft.exchange.webservices.data.HttpClientWebRequest.java

/**
 * Prepare connection/*w ww .  j  av a  2s .c o m*/
 *
 * @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:com.ea.core.bridge.ws.rest.client.AbstractRestClient.java

public AbstractRestClient(URL httpUrl) {
    super(httpUrl);

    HttpMessageParserFactory<HttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() {
        @Override/* ww  w . ja  v  a2  s .c om*/
        public HttpMessageParser<HttpResponse> create(SessionInputBuffer buffer,
                MessageConstraints constraints) {
            LineParser lineParser = new BasicLineParser() {
                @Override
                public Header parseHeader(final CharArrayBuffer buffer) {
                    try {
                        return super.parseHeader(buffer);
                    } catch (ParseException ex) {
                        return new BasicHeader(buffer.toString(), null);
                    }
                }
            };
            return new DefaultHttpResponseParser(buffer, lineParser, DefaultHttpResponseFactory.INSTANCE,
                    constraints) {
                @Override
                protected boolean reject(final CharArrayBuffer line, int count) {
                    // try to ignore all garbage preceding a status line infinitely
                    return false;
                }
            };
        }
    };
    HttpMessageWriterFactory<HttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory();

    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory(
            requestWriterFactory, responseParserFactory);

    SSLContext sslcontext = SSLContexts.createSystemDefault();
    X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier();

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext, hostnameVerifier)).build();

    DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
        @Override
        public InetAddress[] resolve(final String host) throws UnknownHostException {
            if (host.equalsIgnoreCase("myhost") || host.equalsIgnoreCase("localhost")) {
                return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
            } else {
                return super.resolve(host);
            }
        }

    };

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry, connFactory, dnsResolver);

    SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
    connManager.setDefaultSocketConfig(socketConfig);
    connManager.setSocketConfig(new HttpHost("somehost", 80), socketConfig);

    MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200)
            .setMaxLineLength(2000).build();
    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
            .setMessageConstraints(messageConstraints).build();
    connManager.setDefaultConnectionConfig(connectionConfig);
    connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT);
    connManager.setMaxTotal(100);
    connManager.setDefaultMaxPerRoute(10);
    connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20);

    CookieStore cookieStore = new BasicCookieStore();
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH)
            .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).setConnectionRequestTimeout(3000)
            .setConnectTimeout(3000).setSocketTimeout(3000).build();

    client = HttpClients.custom().setConnectionManager(connManager).setDefaultCookieStore(cookieStore)
            .setDefaultCredentialsProvider(credentialsProvider)
            //            .setProxy(new HttpHost("myproxy", 8080))
            .setDefaultRequestConfig(defaultRequestConfig).build();
}

From source file:com.jfrog.bintray.client.impl.HttpClientConfigurator.java

private void configureProxy(ProxyConfig proxy) {
    if (proxy != null) {
        config.setProxy(new HttpHost(proxy.getHost(), proxy.getPort()));
        if (proxy.getUserName() != null) {
            Credentials creds = null;//from   w w w. j  ava2 s .  c o  m
            if (proxy.getNtDomain() == null) {
                creds = new UsernamePasswordCredentials(proxy.getUserName(), proxy.getPassword());
                List<String> authPrefs = Arrays.asList(AuthSchemes.DIGEST, AuthSchemes.BASIC, AuthSchemes.NTLM);
                config.setProxyPreferredAuthSchemes(authPrefs);

                // preemptive proxy authentication
                builder.addInterceptorFirst(new ProxyPreemptiveAuthInterceptor());
            } else {
                try {
                    String ntHost = StringUtils.isBlank(proxy.getNtHost())
                            ? InetAddress.getLocalHost().getHostName()
                            : proxy.getNtHost();
                    creds = new NTCredentials(proxy.getUserName(), proxy.getPassword(), ntHost,
                            proxy.getNtDomain());
                } catch (UnknownHostException e) {
                    log.error("Failed to determine required local hostname for NTLM credentials.", e);
                }
            }
            if (creds != null) {
                credsProvider.setCredentials(
                        new AuthScope(proxy.getHost(), proxy.getPort(), AuthScope.ANY_REALM), creds);
                if (proxy.getRedirectToHosts() != null) {
                    for (String hostName : proxy.getRedirectToHosts()) {
                        credsProvider.setCredentials(
                                new AuthScope(hostName, AuthScope.ANY_PORT, AuthScope.ANY_REALM), creds);
                    }
                }
            }
        }
    }
}

From source file:org.sonatype.nexus.apachehttpclient.Hc4ProviderBase.java

protected 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  ww .  jav  a 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:io.mandrel.requests.http.ApacheHttpRequester.java

public void init() {

    available = new Semaphore(maxParallel(), true);

    SSLContext sslContext = SSLContexts.createSystemDefault();
    HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();

    Registry<ConnectionSocketFactory> sessionStrategyRegistry = RegistryBuilder
            .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", new SSLConnectionSocketFactory(sslContext, hostnameVerifier)).build();

    DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
        @Override//from  ww w  .ja v a  2  s.  c o  m
        public InetAddress[] resolve(final String host) throws UnknownHostException {
            if (host.equalsIgnoreCase("localhost")) {
                return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
            } else {
                return new InetAddress[] { nameResolver().resolve(host) };
            }
        }
    };

    // Create a connection manager with custom configuration.
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
            sessionStrategyRegistry, dnsResolver);

    // Create message constraints
    MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(maxHeaderCount)
            .setMaxLineLength(maxLineLength).build();

    // Create connection configuration
    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
            .setMessageConstraints(messageConstraints).build();
    connManager.setDefaultConnectionConfig(connectionConfig);

    // Configure total max or per route limits for persistent connections
    // that can be kept in the pool or leased by the connection manager.
    connManager.setMaxTotal(maxPersistentConnections());
    connManager.setDefaultMaxPerRoute(maxPersistentConnections());

    // TODO
    // Use custom credentials provider if necessary.
    // CredentialsProvider credentialsProvider = new
    // BasicCredentialsProvider();

    // Create global request configuration
    defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT)
            .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).setMaxRedirects(maxRedirects())
            .setSocketTimeout(socketTimeout()).setConnectTimeout(connectTimeout())
            .setConnectionRequestTimeout(requestTimeOut()).setRedirectsEnabled(followRedirects()).build();

    // Create an HttpClient with the given custom dependencies and
    // configuration.
    client = HttpClients.custom().setConnectionManager(connManager)
            // .setDefaultCredentialsProvider(credentialsProvider)
            .setDefaultRequestConfig(defaultRequestConfig).build();
}