Example usage for org.apache.http.client.params AuthPolicy NTLM

List of usage examples for org.apache.http.client.params AuthPolicy NTLM

Introduction

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

Prototype

String NTLM

To view the source code for org.apache.http.client.params AuthPolicy 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:com.eviware.soapui.support.httpclient.JCIFSTest.java

@Test
public void test() throws ParseException, IOException {
    try {//from  ww w .j av  a2 s.c  o m
        DefaultHttpClient httpClient = new DefaultHttpClient();

        httpClient.getAuthSchemes().register(AuthPolicy.NTLM, new NTLMSchemeFactory());
        httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, new NTLMSchemeFactory());

        NTCredentials creds = new NTCredentials("testuser", "kebabsalladT357", "", "");
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

        HttpHost target = new HttpHost("dev-appsrv01.eviware.local", 81, "http");
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpget = new HttpGet("/");

        HttpResponse response1 = httpClient.execute(target, httpget, localContext);
        HttpEntity entity1 = response1.getEntity();

        //      System.out.println( "----------------------------------------" );
        //System.out.println( response1.getStatusLine() );
        //      System.out.println( "----------------------------------------" );
        if (entity1 != null) {
            //System.out.println( EntityUtils.toString( entity1 ) );
        }
        //      System.out.println( "----------------------------------------" );

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

        Assert.assertEquals(response1.getStatusLine().getStatusCode(), 200);
    } catch (UnknownHostException e) {
        /* ignore */
    } catch (HttpHostConnectException e) {
        /* ignore */
    } catch (SocketException e) {
        /* ignore */
    }

    Assert.assertTrue(true);
}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpAuthenticationRequestFilterTest.java

@Test
public void selectingAuthTypeNtlmReturnsNtlmIfNtlmRequested() {
    selectAuthMethod(CredentialsConfig.AuthType.NTLM);

    filter.filterAbstractHttpRequest(null, wsdlRequest);

    AuthScheme scheme = getSchemeFor(AuthPolicy.NTLM);
    assertThat(scheme, instanceOf(NTLMScheme.class));
}

From source file:org.jasig.portlet.calendar.adapter.exchange.NtlmAuthHttpClient.java

@Override
public void afterPropertiesSet() throws Exception {
    if (authenticationSchemes == null) {
        authenticationSchemes = new HashMap<String, AuthSchemeFactory>();
        final AuthSchemeFactory fac = new NTLMSchemeFactory();
        final AuthSchemeFactory bfac = new BasicSchemeFactory();
        authenticationSchemes.put(AuthPolicy.BASIC, bfac);
        authenticationSchemes.put(AuthPolicy.NTLM, fac);
        authenticationSchemes.put(AuthPolicy.SPNEGO, fac);
    }/*from  w w  w  . j a  v  a2s  .  com*/
    setup();
    if (log.isDebugEnabled()) {
        log.debug("Support is available for the following authenticationSchemes="
                + authenticationSchemes.keySet());
    }
}

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.  j a  v  a  2s  .  com*/
        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:com.eviware.soapui.impl.wsdl.submit.filters.HttpAuthenticationRequestFilterTest.java

@Test
public void selectingAuthTypeSpnegoReturnsNtlmIfNtlmRequested() {
    selectAuthMethod(CredentialsConfig.AuthType.SPNEGO_KERBEROS);

    filter.filterAbstractHttpRequest(null, wsdlRequest);

    AuthScheme scheme = getSchemeFor(AuthPolicy.NTLM);
    assertThat(scheme, instanceOf(NTLMScheme.class));
}

From source file:org.gradle.api.internal.artifacts.repositories.transport.http.HttpClientConfigurer.java

private void useCredentials(DefaultHttpClient httpClient, PasswordCredentials credentials, String host,
        int port) {
    Credentials basicCredentials = new UsernamePasswordCredentials(credentials.getUsername(),
            credentials.getPassword());//from   ww  w. ja  va2s . c om
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, port), basicCredentials);

    NTLMCredentials ntlmCredentials = new NTLMCredentials(credentials);
    Credentials ntCredentials = new NTCredentials(ntlmCredentials.getUsername(), ntlmCredentials.getPassword(),
            ntlmCredentials.getWorkstation(), ntlmCredentials.getDomain());
    httpClient.getCredentialsProvider()
            .setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM, AuthPolicy.NTLM), ntCredentials);

    LOGGER.debug("Using {} and {} for authenticating against '{}:{}'",
            new Object[] { credentials, ntlmCredentials, host, port });
}

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;/* w w w. j a v  a  2 s . co  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:nl.esciencecenter.octopus.webservice.JobLauncherService.java

/**
 * Adds MAC Access Authentication scheme to http client and registers list of MAC credentials with http client.
 *
 * Http client will use MAC Access Authentication when url is in scope of given MAC credentials.
 *
 * @param httpClient//  w w w .  j  a  v  a  2  s  .  c o  m
 * @param macs
 * @return httpClient with MAC access authentication and credentials injected.
 */
public static AbstractHttpClient macifyHttpClient(AbstractHttpClient httpClient,
        ImmutableList<MacCredential> macs) {

    // Add MAC scheme
    httpClient.getAuthSchemes().register(MacScheme.SCHEME_NAME, new MacSchemeFactory());

    // Add configured MAC id/key pairs.
    CredentialsProvider credentialProvider = httpClient.getCredentialsProvider();
    for (MacCredential mac : macs) {
        credentialProvider.setCredentials(mac.getAuthScope(), mac);
    }

    // Add MAC scheme to ordered list of supported authentication schemes
    // See HTTP authentication parameters chapter on
    // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html
    List<String> authSchemes = Collections.unmodifiableList(Arrays.asList(new String[] { MacScheme.SCHEME_NAME,
            AuthPolicy.SPNEGO, AuthPolicy.KERBEROS, AuthPolicy.NTLM, AuthPolicy.DIGEST, AuthPolicy.BASIC }));
    httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authSchemes);

    return httpClient;
}