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

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

Introduction

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

Prototype

public SPNegoSchemeFactory() 

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  a va  2  s .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.dlmu.heipacker.crawler.client.ClientKerberosAuthentication.java

public static void main(String[] args) throws Exception {

    System.setProperty("java.security.auth.login.config", "login.conf");
    System.setProperty("java.security.krb5.conf", "krb5.conf");
    System.setProperty("sun.security.krb5.debug", "true");
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/* w  w  w  .ja  va 2  s. c  om*/
        httpclient.getAuthSchemes().register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory());

        Credentials use_jaas_creds = new Credentials() {

            public String getPassword() {
                return null;
            }

            public Principal getUserPrincipal() {
                return null;
            }

        };

        httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1, null), use_jaas_creds);

        HttpUriRequest request = new HttpGet("http://kerberoshost/");
        HttpResponse response = httpclient.execute(request);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        System.out.println("----------------------------------------");
        if (entity != null) {
            System.out.println(EntityUtils.toString(entity));
        }
        System.out.println("----------------------------------------");

        // This ensures the connection gets released back to the manager
        EntityUtils.consume(entity);

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

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;/*from w  w w . ja  va 2 s  . 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.jaeksoft.searchlib.crawler.web.spider.HttpAbstract.java

public HttpAbstract(String userAgent, boolean bFollowRedirect, ProxyHandler proxyHandler) {
    HttpClientBuilder builder = HttpClients.custom();

    redirectStrategy = new DefaultRedirectStrategy();

    if (userAgent != null) {
        userAgent = userAgent.trim();//from   w  ww .j a va  2  s.c o m
        if (userAgent.length() > 0)
            builder.setUserAgent(userAgent);
        else
            userAgent = null;
    }
    if (!bFollowRedirect)
        builder.disableRedirectHandling();

    this.proxyHandler = proxyHandler;

    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();

    credentialsProvider = new BasicCredentialsProvider();
    builder.setDefaultCredentialsProvider(credentialsProvider);

    cookieStore = new BasicCookieStore();
    builder.setDefaultCookieStore(cookieStore);

    builder.setDefaultCredentialsProvider(credentialsProvider);
    builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);

    httpClient = builder.build();

}

From source file:org.elasticsearch.xpack.security.authc.kerberos.SpnegoHttpClientConfigCallbackHandler.java

private void setupSpnegoAuthSchemeSupport(HttpAsyncClientBuilder httpClientBuilder) {
    final Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()).build();

    final GSSManager gssManager = GSSManager.getInstance();
    try {//from w  w  w  .ja  v a2s  .c om
        final GSSName gssUserPrincipalName = gssManager.createName(userPrincipalName, GSSName.NT_USER_NAME);
        login();
        final AccessControlContext acc = AccessController.getContext();
        final GSSCredential credential = doAsPrivilegedWrapper(loginContext.getSubject(),
                (PrivilegedExceptionAction<GSSCredential>) () -> gssManager.createCredential(
                        gssUserPrincipalName, GSSCredential.DEFAULT_LIFETIME, SPNEGO_OID,
                        GSSCredential.INITIATE_ONLY),
                acc);

        final KerberosCredentialsProvider credentialsProvider = new KerberosCredentialsProvider();
        credentialsProvider.setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthSchemes.SPNEGO),
                new KerberosCredentials(credential));
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    } catch (GSSException e) {
        throw new RuntimeException(e);
    } catch (PrivilegedActionException e) {
        throw new RuntimeException(e.getCause());
    }
    httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
}

From source file:org.brunocvcunha.taskerbox.core.http.TaskerboxHttpBox.java

/**
 * Build a new HTTP Client for the given parameters
 *
 * @param params/*from  ww  w.  j  a v a 2 s . com*/
 * @return
 */
public DefaultHttpClient buildNewHttpClient(HttpParams params) {
    PoolingClientConnectionManager cxMgr = new PoolingClientConnectionManager(
            SchemeRegistryFactory.createDefault());
    cxMgr.setMaxTotal(100);
    cxMgr.setDefaultMaxPerRoute(20);

    DefaultHttpClient httpClient = new DefaultHttpClient(cxMgr, params);
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
            "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36");
    // httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
    // CookiePolicy.BROWSER_COMPATIBILITY);
    if (this.useNtlm) {
        httpClient.getAuthSchemes().register("NTLM", new NTLMSchemeFactory());
        httpClient.getAuthSchemes().register("BASIC", new BasicSchemeFactory());
        httpClient.getAuthSchemes().register("DIGEST", new DigestSchemeFactory());
        httpClient.getAuthSchemes().register("SPNEGO", new SPNegoSchemeFactory());
        httpClient.getAuthSchemes().register("KERBEROS", new KerberosSchemeFactory());
    }

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, getTrustingManager(), new java.security.SecureRandom());
        SSLSocketFactory socketFactory = new SSLSocketFactory(sc);
        Scheme sch = new Scheme("https", 443, socketFactory);
        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    if (this.useProxy) {
        if (this.proxySocks) {

            log.info("Using proxy socks " + this.socksHost + ":" + this.socksPort);

            System.setProperty("socksProxyHost", this.socksHost);
            System.setProperty("socksProxyPort", String.valueOf(this.socksPort));

        } else {
            HttpHost proxy = new HttpHost(this.proxyHost, this.proxyPort);
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

            if (this.authProxy) {

                List<String> authPreferences = new ArrayList<>();

                if (this.ntlmProxy) {

                    NTCredentials creds = new NTCredentials(this.proxyUser, this.proxyPassword,
                            this.proxyWorkstation, this.proxyDomain);
                    httpClient.getCredentialsProvider()
                            .setCredentials(new AuthScope(this.proxyHost, this.proxyPort), creds);
                    // httpClient.getCredentialsProvider().setCredentials(
                    // AuthScope.ANY, creds);

                    authPreferences.add(AuthPolicy.NTLM);
                } else {
                    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(this.proxyUser,
                            this.proxyPassword);
                    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

                    authPreferences.add(AuthPolicy.BASIC);
                }

                httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authPreferences);
            }
        }

    }

    return httpClient;
}

From source file:eu.fthevenet.binjr.data.adapters.HttpDataAdapterBase.java

protected CloseableHttpClient httpClientFactory() throws CannotInitializeDataAdapterException {
    try {//  w  w  w  .jav a  2s .c o m
        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(createSslCustomContext(), null, null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        RegistryBuilder<AuthSchemeProvider> schemeProviderBuilder = RegistryBuilder.create();
        schemeProviderBuilder.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(null, -1, null), new Credentials() {
            @Override
            public Principal getUserPrincipal() {
                return null;
            }

            @Override
            public String getPassword() {
                return null;
            }
        });

        return HttpClients.custom().setDefaultAuthSchemeRegistry(schemeProviderBuilder.build())
                .setDefaultCredentialsProvider(credsProvider).setSSLSocketFactory(csf).build();
    } catch (Exception e) {
        throw new CannotInitializeDataAdapterException(
                "Could not initialize adapter to source '" + this.getSourceName() + "': " + e.getMessage(), e);
    }
}

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 a va  2 s .c  o  m
        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:org.apache.zeppelin.livy.BaseLivyInterpreter.java

private RestTemplate createRestTemplate() {
    String keytabLocation = getProperty("zeppelin.livy.keytab");
    String principal = getProperty("zeppelin.livy.principal");
    boolean isSpnegoEnabled = StringUtils.isNotEmpty(keytabLocation) && StringUtils.isNotEmpty(principal);

    HttpClient httpClient = null;//  w  ww  .ja va 2 s . c om
    if (livyURL.startsWith("https:")) {
        String keystoreFile = getProperty("zeppelin.livy.ssl.trustStore");
        String password = getProperty("zeppelin.livy.ssl.trustStorePassword");
        if (StringUtils.isBlank(keystoreFile)) {
            throw new RuntimeException("No zeppelin.livy.ssl.trustStore specified for livy ssl");
        }
        if (StringUtils.isBlank(password)) {
            throw new RuntimeException("No zeppelin.livy.ssl.trustStorePassword specified " + "for livy ssl");
        }
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(keystoreFile);
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(new FileInputStream(keystoreFile), password.toCharArray());
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore).build();
            SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
            HttpClientBuilder httpClientBuilder = HttpClients.custom().setSSLSocketFactory(csf);
            RequestConfig reqConfig = new RequestConfig() {
                @Override
                public boolean isAuthenticationEnabled() {
                    return true;
                }
            };
            httpClientBuilder.setDefaultRequestConfig(reqConfig);
            Credentials credentials = new Credentials() {
                @Override
                public String getPassword() {
                    return null;
                }

                @Override
                public Principal getUserPrincipal() {
                    return null;
                }
            };
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(AuthScope.ANY, credentials);
            httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
            if (isSpnegoEnabled) {
                Registry<AuthSchemeProvider> authSchemeProviderRegistry = RegistryBuilder
                        .<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
                        .build();
                httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeProviderRegistry);
            }

            httpClient = httpClientBuilder.build();
        } catch (Exception e) {
            throw new RuntimeException("Failed to create SSL HttpClient", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    LOGGER.error("Failed to close keystore file", e);
                }
            }
        }
    }

    RestTemplate restTemplate = null;
    if (isSpnegoEnabled) {
        if (httpClient == null) {
            restTemplate = new KerberosRestTemplate(keytabLocation, principal);
        } else {
            restTemplate = new KerberosRestTemplate(keytabLocation, principal, httpClient);
        }
    } else {
        if (httpClient == null) {
            restTemplate = new RestTemplate();
        } else {
            restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
        }
    }
    restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
    return restTemplate;
}

From source file:org.apache.http.impl.client.AbstractHttpClient.java

protected AuthSchemeRegistry createAuthSchemeRegistry() {
    final AuthSchemeRegistry registry = new AuthSchemeRegistry();
    registry.register(AuthPolicy.BASIC, new BasicSchemeFactory());
    registry.register(AuthPolicy.DIGEST, new DigestSchemeFactory());
    registry.register(AuthPolicy.NTLM, new NTLMSchemeFactory());
    registry.register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory());
    registry.register(AuthPolicy.KERBEROS, new KerberosSchemeFactory());
    return registry;
}