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:com.android.sdklib.internal.repository.UrlOpener.java

private static InputStream openWithHttpClient(String url, ITaskMonitor monitor)
        throws IOException, ClientProtocolException, CanceledByUserException {
    UserCredentials result = null;/*from  www .  j  a v  a2 s .c o  m*/
    String realm = null;

    // use the simple one
    final DefaultHttpClient httpClient = new DefaultHttpClient();

    // create local execution context
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpget = new HttpGet(url);

    // retrieve local java configured network in case there is the need to
    // authenticate a proxy
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    // Set preference order for authentication options.
    // In particular, we don't add AuthPolicy.SPNEGO, which is given preference over NTLM in
    // servers that support both, as it is more secure. However, we don't seem to handle it
    // very well, so we leave it off the list.
    // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html for
    // more info.
    List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.BASIC);
    authpref.add(AuthPolicy.DIGEST);
    authpref.add(AuthPolicy.NTLM);
    httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);

    boolean trying = true;
    // loop while the response is being fetched
    while (trying) {
        // connect and get status code
        HttpResponse response = httpClient.execute(httpget, localContext);
        int statusCode = response.getStatusLine().getStatusCode();

        // check whether any authentication is required
        AuthState authenticationState = null;
        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            // Target host authentication required
            authenticationState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
        }
        if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            // Proxy authentication required
            authenticationState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
        }
        if (statusCode == HttpStatus.SC_OK) {
            // in case the status is OK and there is a realm and result,
            // cache it
            if (realm != null && result != null) {
                sRealmCache.put(realm, result);
            }
        }

        // there is the need for authentication
        if (authenticationState != null) {

            // get scope and realm
            AuthScope authScope = authenticationState.getAuthScope();

            // If the current realm is different from the last one it means
            // a pass was performed successfully to the last URL, therefore
            // cache the last realm
            if (realm != null && !realm.equals(authScope.getRealm())) {
                sRealmCache.put(realm, result);
            }

            realm = authScope.getRealm();

            // in case there is cache for this Realm, use it to authenticate
            if (sRealmCache.containsKey(realm)) {
                result = sRealmCache.get(realm);
            } else {
                // since there is no cache, request for login and password
                result = monitor.displayLoginCredentialsPrompt("Site Authentication",
                        "Please login to the following domain: " + realm
                                + "\n\nServer requiring authentication:\n" + authScope.getHost());
                if (result == null) {
                    throw new CanceledByUserException("User canceled login dialog.");
                }
            }

            // retrieve authentication data
            String user = result.getUserName();
            String password = result.getPassword();
            String workstation = result.getWorkstation();
            String domain = result.getDomain();

            // proceed in case there is indeed a user
            if (user != null && user.length() > 0) {
                Credentials credentials = new NTCredentials(user, password, workstation, domain);
                httpClient.getCredentialsProvider().setCredentials(authScope, credentials);
                trying = true;
            } else {
                trying = false;
            }
        } else {
            trying = false;
        }

        HttpEntity entity = response.getEntity();

        if (entity != null) {
            if (trying) {
                // in case another pass to the Http Client will be performed, close the entity.
                entity.getContent().close();
            } else {
                // since no pass to the Http Client is needed, retrieve the
                // entity's content.

                // Note: don't use something like a BufferedHttpEntity since it would consume
                // all content and store it in memory, resulting in an OutOfMemory exception
                // on a large download.

                return new FilterInputStream(entity.getContent()) {
                    @Override
                    public void close() throws IOException {
                        super.close();

                        // since Http Client is no longer needed, close it
                        httpClient.getConnectionManager().shutdown();
                    }
                };
            }
        }
    }

    // We get here if we did not succeed. Callers do not expect a null result.
    httpClient.getConnectionManager().shutdown();
    throw new FileNotFoundException(url);
}

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

private static void configureAuthentication(final DefaultHttpClient httpClient, final String ctxPrefix,
        final RemoteStorageContext ctx, final RemoteAuthenticationSettings ras, final Logger logger,
        final String authScope) {
    if (ras != null) {
        List<String> authorisationPreference = new ArrayList<String>(2);
        authorisationPreference.add(AuthPolicy.DIGEST);
        authorisationPreference.add(AuthPolicy.BASIC);

        Credentials credentials = null;//from  w  w w .  j ava2 s .c om

        if (ras instanceof ClientSSLRemoteAuthenticationSettings) {
            // ClientSSLRemoteAuthenticationSettings cras = (ClientSSLRemoteAuthenticationSettings) ras;

            // TODO - implement this
        } else if (ras instanceof NtlmRemoteAuthenticationSettings) {
            final NtlmRemoteAuthenticationSettings nras = (NtlmRemoteAuthenticationSettings) ras;

            // Using NTLM auth, adding it as first in policies
            authorisationPreference.add(0, AuthPolicy.NTLM);

            logger(logger).info("... {}authentication setup for NTLM domain '{}'", authScope,
                    nras.getNtlmDomain());

            credentials = new NTCredentials(nras.getUsername(), nras.getPassword(), nras.getNtlmHost(),
                    nras.getNtlmDomain());

            ctx.putContextObject(ctxPrefix + CTX_KEY_NTLM_IS_IN_USE, Boolean.TRUE);
        } else if (ras instanceof UsernamePasswordRemoteAuthenticationSettings) {
            UsernamePasswordRemoteAuthenticationSettings uras = (UsernamePasswordRemoteAuthenticationSettings) ras;

            // Using Username/Pwd auth, will not add NTLM
            logger(logger).info("... {}authentication setup for remote storage with username '{}'", authScope,
                    uras.getUsername());

            credentials = new UsernamePasswordCredentials(uras.getUsername(), uras.getPassword());
        }

        if (credentials != null) {
            httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
        }

        httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authorisationPreference);
    }
}

From source file:com.amazonaws.util.HttpUtils.java

/**
 * Fetches a file from the URI given and returns an input stream to it.
 *
 * @param uri the uri of the file to fetch
 * @param config optional configuration overrides
 * @return an InputStream containing the retrieved data
 * @throws IOException on error/*from   w  w w.ja  va  2 s .  com*/
 */
public static InputStream fetchFile(final URI uri, final ClientConfiguration config) throws IOException {

    HttpParams httpClientParams = new BasicHttpParams();
    HttpProtocolParams.setUserAgent(httpClientParams, getUserAgent(config));

    HttpConnectionParams.setConnectionTimeout(httpClientParams, getConnectionTimeout(config));
    HttpConnectionParams.setSoTimeout(httpClientParams, getSocketTimeout(config));

    DefaultHttpClient httpclient = new DefaultHttpClient(httpClientParams);

    if (config != null) {
        String proxyHost = config.getProxyHost();
        int proxyPort = config.getProxyPort();

        if (proxyHost != null && proxyPort > 0) {

            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

            if (config.getProxyUsername() != null && config.getProxyPassword() != null) {

                httpclient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort),
                        new NTCredentials(config.getProxyUsername(), config.getProxyPassword(),
                                config.getProxyWorkstation(), config.getProxyDomain()));
            }
        }
    }

    HttpResponse response = httpclient.execute(new HttpGet(uri));

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new IOException("Error fetching file from " + uri + ": " + response);
    }

    return new HttpClientWrappingInputStream(httpclient, response.getEntity().getContent());
}

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

/**
 * Prepare asynchronous connection./* w ww.j  a  v a 2s  .com*/
 *
 * @throws microsoft.exchange.webservices.data.EWSHttpException throws EWSHttpException
 */
public void prepareAsyncConnection() throws EWSHttpException {
    try {
        //ssl config
        HttpClientBuilder builder = HttpClients.custom();
        builder.setConnectionManager(this.httpClientConnMng);
        builder.setSchemePortResolver(new DefaultSchemePortResolver());

        EwsSSLProtocolSocketFactory factory = EwsSSLProtocolSocketFactory.build(trustManger);
        builder.setSSLSocketFactory(factory);
        builder.setSslcontext(factory.getContext());

        //create the cookie store
        if (cookieStore == null) {
            cookieStore = new BasicCookieStore();
        }
        builder.setDefaultCookieStore(cookieStore);

        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.setConnectionRequestTimeout(getTimeout());
        rcBuilder.setConnectTimeout(getTimeout());
        rcBuilder.setSocketTimeout(getTimeout());

        // fix issue #144 + #160: if we used NTCredentials from above: these are NT credentials
        ArrayList<String> authPrefs = new ArrayList<String>();
        authPrefs.add(AuthSchemes.NTLM);
        rcBuilder.setTargetPreferredAuthSchemes(authPrefs);
        //

        builder.setDefaultRequestConfig(rcBuilder.build());

        //HttpClientParams.setRedirecting(client.getParams(), isAllowAutoRedirect()); by default it follows redirects
        //create the client and execute requests
        client = builder.build();
        httpPostReq = new HttpPost(getUrl().toString());
        response = client.execute(httpPostReq);
    } catch (IOException e) {
        client = null;
        httpPostReq = null;
        throw new EWSHttpException("Unable to open connection to " + this.getUrl());
    } catch (Exception e) {
        client = null;
        httpPostReq = null;
        e.printStackTrace();
        throw new EWSHttpException("SSL problem " + this.getUrl());
    }
}

From source file:org.eclipse.mylyn.commons.repositories.http.core.HttpUtil.java

public static NTCredentials getNtCredentials(UserCredentials credentials, String workstation) {
    String username = credentials.getUserName();
    int i = username.indexOf("\\"); //$NON-NLS-1$
    if (i > 0 && i < username.length() - 1) {
        //         try {
        //            InetAddress localHost = InetAddress.getLocalHost();
        //            if (localHost != null) {
        //               hostName = localHost.getHostName();
        //            }
        //         } catch (UnknownHostException e) {
        //            StatusHandler.log(new Status(IStatus.ERROR, ID_PLUGIN,
        //                  "Unable to get hostname.  Defaulting to servers host.", e));
        //         }
        return new NTCredentials(username.substring(i + 1), credentials.getPassword(), workstation,
                username.substring(0, i));
    }//from ww  w.ja v a2 s.co m
    return null;
}

From source file:com.intuit.tank.httpclient4.TankHttpClient4.java

@Override
public void addAuth(AuthCredentials creds) {
    String host = (StringUtils.isBlank(creds.getHost()) || "*".equals(creds.getHost())) ? AuthScope.ANY_HOST
            : creds.getHost();/*from  w  ww. j  av  a  2 s  .  c  o m*/
    String realm = (StringUtils.isBlank(creds.getRealm()) || "*".equals(creds.getRealm())) ? AuthScope.ANY_REALM
            : creds.getRealm();
    int port = NumberUtils.toInt(creds.getPortString(), AuthScope.ANY_PORT);
    String scheme = creds.getScheme() != null ? creds.getScheme().getRepresentation() : AuthScope.ANY_SCHEME;
    AuthScope scope = new AuthScope(host, port, realm, scheme);
    if (AuthScheme.NTLM == creds.getScheme()) {
        context.getCredentialsProvider().setCredentials(scope,
                new NTCredentials(creds.getUserName(), creds.getPassword(), "tank-test", creds.getRealm()));
    } else {
        context.getCredentialsProvider().setCredentials(scope,
                new UsernamePasswordCredentials(creds.getUserName(), creds.getPassword()));
    }

}

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.ja  va 2  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:crawler.java.edu.uci.ics.crawler4j.fetcher.PageFetcher.java

/**
 * Do NT auth for Microsoft AD sites.// w w w  . jav a  2s. c  o m
 */
private void doNtLogin(NtAuthInfo authInfo) {
    logger.info("NT authentication for: " + authInfo.getLoginTarget());
    HttpHost targetHost = new HttpHost(authInfo.getHost(), authInfo.getPort(), authInfo.getProtocol());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    try {
        credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new NTCredentials(authInfo.getUsername(), authInfo.getPassword(),
                        InetAddress.getLocalHost().getHostName(), authInfo.getDomain()));
    } catch (UnknownHostException e) {
        logger.error("Error creating NT credentials", e);
    }
    httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
}

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

/**
 * Build a new HTTP Client for the given parameters
 *
 * @param params// w w w  .  jav  a  2  s . c  om
 * @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:com.allstate.client.core.SoapClient.java

private void configureAuthentication(URI uri, Security security) {
    if (security.isAuthEnabled()) {
        AuthScope scope = new AuthScope(uri.getHost(), uri.getPort());
        Credentials credentials = null;//from   w  w  w .  j a  v  a 2  s . co  m
        if (security.isAuthBasic()) {
            credentials = new UsernamePasswordCredentials(security.getAuthUsername(),
                    security.getAuthPassword());
        } else if (security.isAuthDigest()) {
            credentials = new UsernamePasswordCredentials(security.getAuthUsername(),
                    security.getAuthPassword());
        } else if (security.isAuthNtlm()) {
            // TODO
            credentials = new NTCredentials(security.getAuthUsername(), security.getAuthPassword(), null, null);
        } else if (security.isAuthSpnego()) {
            // TODO
        }
        client.getCredentialsProvider().setCredentials(scope, credentials);
    }
}