Example usage for org.apache.http.impl.auth NTLMSchemeFactory NTLMSchemeFactory

List of usage examples for org.apache.http.impl.auth NTLMSchemeFactory NTLMSchemeFactory

Introduction

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

Prototype

NTLMSchemeFactory

Source Link

Usage

From source file:forcalibre.ClientProxyAuthentication.java

public static void main(String[] args) throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(PROXY_HOST, PROXY_PORT),
            ///new UsernamePasswordCredentials("vimpelcom_main\\vyualeksandrov", "s1teRlin9g19")
            new NTCredentials("vyualeksandrov", "s1teRlin9g19", PROXY_HOST, "vimpelcom_main"));

    Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
            .register(AuthSchemes.BASIC, new BasicSchemeFactory())
            .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
            .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build();

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry)
            .setDefaultCredentialsProvider(credsProvider).build();

    try {//from   w w w  .  j  ava2s.  com
        //            HttpHost target = new HttpHost("www.verisign.com", 443, "https");
        //            HttpHost proxy = new HttpHost("localhost", 8080);

        HttpHost target = new HttpHost(TARGET_HOST, 80, "http");
        HttpHost proxy = new HttpHost(PROXY_HOST, PROXY_PORT);

        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        HttpGet httpget = new HttpGet("/");
        httpget.setConfig(config);

        System.out.println("Executing request " + httpget.getRequestLine() + " to " + target + " via " + proxy);

        CloseableHttpResponse response = httpclient.execute(target, httpget);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.kms.core.io.HttpUtil_In.java

public static CloseableHttpClient getHttpClient(final String SoeID, final String Password, final int type) {
    CloseableHttpClient httpclient;/* w  w w  . ja  v a 2s .c o  m*/

    // Auth Scheme 
    final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
            .register(AuthSchemes.BASIC, new BasicSchemeFactory())
            .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
            .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build();

    // NTLM  
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), //AuthScope("localhost", 8080),
            new NTCredentials(SoeID, Password, "dummy", "APAC"));
    //new NTCredentials( SoeID, Password,"APACKR081WV058", "APAC" ));

    // ------------- cookie start ------------------------
    // Auction   
    // Create a local instance of cookie store
    final CookieStore cookieStore = new BasicCookieStore();

    //       Cookie  .
    final BasicClientCookie cookie = new BasicClientCookie("songdal_view", "YES");
    cookie.setVersion(0);
    cookie.setDomain(".scourt.go.kr");
    cookie.setPath("/");
    cookieStore.addCookie(cookie);

    // ------------- cookie end ------------------------

    if (type == 0) // TYPE.AuctionInput
    {
        // HTTP Client 
        httpclient = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry)
                .setDefaultCredentialsProvider(credsProvider).build();
    } else // SagunInput
    {
        // HTTP Client 
        httpclient = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry)
                .setDefaultCredentialsProvider(credsProvider).setDefaultCookieStore(cookieStore).build();
    }

    return httpclient;
}

From source file:com.servoy.extensions.plugins.http.HttpClient.java

public HttpClient(IClientPluginAccess plugin) {
    client = new DefaultHttpClient();
    client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, Boolean.TRUE);
    client.getAuthSchemes().register(AuthPolicy.NTLM, new NTLMSchemeFactory());
    client.getAuthSchemes().register(AuthPolicy.SPNEGO, new NegotiateSchemeFactory());
    this.plugin = plugin;

    try {/*  w  w  w.jav  a 2  s  .c  o  m*/
        final AllowedCertTrustStrategy allowedCertTrustStrategy = new AllowedCertTrustStrategy();
        SSLSocketFactory sf = new SSLSocketFactory(allowedCertTrustStrategy) {
            @Override
            public Socket connectSocket(Socket socket, InetSocketAddress remoteAddress,
                    InetSocketAddress localAddress, HttpParams params)
                    throws IOException, UnknownHostException, ConnectTimeoutException {
                if (socket instanceof SSLSocket) {
                    try {
                        Method s = socket.getClass().getMethod("setHost", String.class);
                        s.invoke(socket, remoteAddress.getHostName());
                    } catch (NoSuchMethodException ex) {
                    } catch (IllegalAccessException ex) {
                    } catch (InvocationTargetException ex) {
                    } catch (IllegalArgumentException ex) {
                    } catch (SecurityException ex) {
                    }
                }
                try {
                    return super.connectSocket(socket, remoteAddress, localAddress, params);
                } catch (SSLPeerUnverifiedException ex) {
                    X509Certificate[] lastCertificates = allowedCertTrustStrategy.getAndClearLastCertificates();
                    if (lastCertificates != null) {
                        // allow for next time
                        if (HttpClient.this.plugin.getApplicationType() == IClientPluginAccess.CLIENT
                                || HttpClient.this.plugin.getApplicationType() == IClientPluginAccess.RUNTIME) {
                            // show dialog
                            CertificateDialog dialog = new CertificateDialog(
                                    ((ISmartRuntimeWindow) HttpClient.this.plugin.getCurrentRuntimeWindow())
                                            .getWindow(),
                                    remoteAddress, lastCertificates);
                            if (dialog.shouldAccept()) {
                                allowedCertTrustStrategy.add(lastCertificates);
                                // try it again now with the new chain.
                                return super.connectSocket(socket, remoteAddress, localAddress, params);
                            }
                        } else {
                            Debug.error("Couldn't connect to " + remoteAddress
                                    + ", please make sure that the ssl certificates of that site are added to the java keystore."
                                    + "Download the keystore in the browser and update the java cacerts file in jre/lib/security: "
                                    + "keytool -import -file downloaded.crt -keystore cacerts");
                        }
                    }
                    throw ex;
                } finally {
                    // always just clear the last request.
                    allowedCertTrustStrategy.getAndClearLastCertificates();
                }

            }
        };
        Scheme https = new Scheme("https", 443, sf); //$NON-NLS-1$
        client.getConnectionManager().getSchemeRegistry().register(https);
    } catch (Exception e) {
        Debug.error("Can't register a https scheme", e); //$NON-NLS-1$
    }
}

From source file:ch.cyberduck.core.http.HttpConnectionPoolBuilder.java

public HttpClientBuilder build(final TranscriptListener listener) {
    // Use HTTP Connect proxy implementation provided here instead of
    // relying on internal proxy support in socket factory
    final Proxy proxy = proxyFinder.find(host);
    if (proxy.getType() == Proxy.Type.HTTP) {
        final HttpHost h = new HttpHost(proxy.getHostname(), proxy.getPort(), Scheme.http.name());
        if (log.isInfoEnabled()) {
            log.info(String.format("Setup proxy %s", h));
        }/*from  w w  w.  j  ava  2  s  . com*/
        builder.setProxy(h);
    }
    if (proxy.getType() == Proxy.Type.HTTPS) {
        final HttpHost h = new HttpHost(proxy.getHostname(), proxy.getPort(), Scheme.https.name());
        if (log.isInfoEnabled()) {
            log.info(String.format("Setup proxy %s", h));
        }
        builder.setProxy(h);
    }
    builder.setUserAgent(new PreferencesUseragentProvider().get());
    final int timeout = preferences.getInteger("connection.timeout.seconds") * 1000;
    builder.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(timeout).build());
    builder.setDefaultRequestConfig(RequestConfig.custom().setRedirectsEnabled(true)
            // Disable use of Expect: Continue by default for all methods
            .setExpectContinueEnabled(false).setAuthenticationEnabled(true).setConnectTimeout(timeout)
            // Sets the timeout in milliseconds used when retrieving a connection from the ClientConnectionManager
            .setConnectionRequestTimeout(preferences.getInteger("http.manager.timeout"))
            .setSocketTimeout(timeout).build());
    final String encoding;
    if (null == host.getEncoding()) {
        encoding = preferences.getProperty("browser.charset.encoding");
    } else {
        encoding = host.getEncoding();
    }
    builder.setDefaultConnectionConfig(
            ConnectionConfig.custom().setBufferSize(preferences.getInteger("http.socket.buffer"))
                    .setCharset(Charset.forName(encoding)).build());
    if (preferences.getBoolean("http.connections.reuse")) {
        builder.setConnectionReuseStrategy(new DefaultConnectionReuseStrategy());
    } else {
        builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
    }
    builder.setRetryHandler(
            new ExtendedHttpRequestRetryHandler(preferences.getInteger("http.connections.retry")));
    if (!preferences.getBoolean("http.compression.enable")) {
        builder.disableContentCompression();
    }
    builder.setRequestExecutor(new LoggingHttpRequestExecutor(listener));
    // Always register HTTP for possible use with proxy. Contains a number of protocol properties such as the
    // default port and the socket factory to be used to create the java.net.Socket instances for the given protocol
    builder.setConnectionManager(this.pool(this.registry().build()));
    builder.setDefaultAuthSchemeRegistry(RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.BASIC,
                    new BasicSchemeFactory(
                            Charset.forName(preferences.getProperty("http.credentials.charset"))))
            .register(AuthSchemes.DIGEST,
                    new DigestSchemeFactory(
                            Charset.forName(preferences.getProperty("http.credentials.charset"))))
            .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
            .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build());
    return builder;
}

From source file:de.codecentric.elasticsearch.plugin.kerberosrealm.AbstractUnitTest.java

protected final CloseableHttpClient getHttpClient(final boolean useSpnego) throws Exception {

    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    final HttpClientBuilder hcb = HttpClients.custom();

    if (useSpnego) {
        //SPNEGO/Kerberos setup
        log.debug("SPNEGO activated");
        final AuthSchemeProvider nsf = new SPNegoSchemeFactory(true);//  new NegotiateSchemeProvider();
        final Credentials jaasCreds = new JaasCredentials();
        credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.SPNEGO), jaasCreds);
        credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM),
                new NTCredentials("Guest", "Guest", "Guest", "Guest"));
        final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                .register(AuthSchemes.SPNEGO, nsf).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build();

        hcb.setDefaultAuthSchemeRegistry(authSchemeRegistry);
    }// w ww .j a va 2 s . co m

    hcb.setDefaultCredentialsProvider(credsProvider);
    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(10 * 1000).build());
    final CloseableHttpClient httpClient = hcb.build();
    return httpClient;
}

From source file:org.apache.maven.wagon.providers.http.AbstractHttpClientWagonFixed.java

private static CloseableHttpClient createClient() {
    return HttpClientBuilder.create() //
            .useSystemProperties() //
            .disableConnectionState() //
            .setConnectionManager(httpClientConnectionManager) //
            //Using Custom Default Schema Registry
            .setDefaultAuthSchemeRegistry(RegistryBuilder.<AuthSchemeProvider>create()
                    .register(AuthSchemes.BASIC, new BasicSchemeFactory())
                    .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
                    .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
                    //Using Custom SPNEGO Factory & FORCE strip port
                    //Kerberos Error: Server not found in Kerberos database (7) - LOOKING_UP_SERVER
                    .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true))
                    .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory(true)).build())
            .build();/*from ww w .  j a v  a 2s. c  o  m*/
}

From source file:com.petalmd.armor.AbstractUnitTest.java

protected final HeaderAwareJestHttpClient getJestClient(final String serverUri, final String username,
        final String password) throws Exception {// http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html

    final CredentialsProvider credsProvider = new BasicCredentialsProvider();

    final HttpClientConfig clientConfig1 = new HttpClientConfig.Builder(serverUri).multiThreaded(true).build();

    // Construct a new Jest client according to configuration via factory
    final HeaderAwareJestClientFactory factory1 = new HeaderAwareJestClientFactory();

    factory1.setHttpClientConfig(clientConfig1);

    final HeaderAwareJestHttpClient c = factory1.getObject();

    final HttpClientBuilder hcb = HttpClients.custom();

    if (username != null) {
        credsProvider.setCredentials(new AuthScope(AuthScope.ANY),
                new UsernamePasswordCredentials(username, password));
    }/*from   w w  w .  j a va  2s.c o m*/

    if (useSpnego) {
        //SPNEGO/Kerberos setup
        log.debug("SPNEGO activated");
        final AuthSchemeProvider nsf = new SPNegoSchemeFactory(true, false);//  new NegotiateSchemeProvider();
        final Credentials jaasCreds = new JaasCredentials();
        credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.SPNEGO), jaasCreds);
        credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM),
                new NTCredentials("Guest", "Guest", "Guest", "Guest"));
        final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                .register(AuthSchemes.SPNEGO, nsf).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build();

        hcb.setDefaultAuthSchemeRegistry(authSchemeRegistry);
    }

    hcb.setDefaultCredentialsProvider(credsProvider);

    if (serverUri.startsWith("https")) {
        log.debug("Configure Jest with SSL");

        final KeyStore myTrustStore = KeyStore.getInstance("JKS");
        myTrustStore.load(new FileInputStream(SecurityUtil.getAbsoluteFilePathFromClassPath("ArmorTS.jks")),
                "changeit".toCharArray());

        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(SecurityUtil.getAbsoluteFilePathFromClassPath("ArmorKS.jks")),
                "changeit".toCharArray());

        final SSLContext sslContext = SSLContexts.custom().useTLS()
                .loadKeyMaterial(keyStore, "changeit".toCharArray()).loadTrustMaterial(myTrustStore).build();

        String[] protocols = null;

        if (enableSSLv3Only) {
            protocols = new String[] { "SSLv3" };
        } else {
            protocols = SecurityUtil.ENABLED_SSL_PROTOCOLS;
        }

        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols,
                SecurityUtil.ENABLED_SSL_CIPHERS, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        hcb.setSSLSocketFactory(sslsf);

    }

    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());

    final CloseableHttpClient httpClient = hcb.build();

    c.setHttpClient(httpClient);
    return c;

}