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:org.apache.axis2.transport.http.impl.httpclient4.HTTPSenderImpl.java

protected void setAuthenticationInfo(AbstractHttpClient agent, MessageContext msgCtx) throws AxisFault {
    HTTPAuthenticator authenticator;//from  w  w w  .  j  a  v  a  2  s.c  o  m
    Object obj = msgCtx.getProperty(HTTPConstants.AUTHENTICATE);
    if (obj != null) {
        if (obj instanceof HTTPAuthenticator) {
            authenticator = (HTTPAuthenticator) obj;

            String username = authenticator.getUsername();
            String password = authenticator.getPassword();
            String host = authenticator.getHost();
            String domain = authenticator.getDomain();

            int port = authenticator.getPort();
            String realm = authenticator.getRealm();

            /* If retrying is available set it first */
            isAllowedRetry = authenticator.isAllowedRetry();

            Credentials creds;

            // TODO : Set preemptive authentication, but its not recommended in HC 4

            if (host != null) {
                if (domain != null) {
                    /* Credentials for NTLM Authentication */
                    agent.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
                    creds = new NTCredentials(username, password, host, domain);
                } else {
                    /* Credentials for Digest and Basic Authentication */
                    creds = new UsernamePasswordCredentials(username, password);
                }
                agent.getCredentialsProvider().setCredentials(new AuthScope(host, port, realm), creds);
            } else {
                if (domain != null) {
                    /*
                     * Credentials for NTLM Authentication when host is
                     * ANY_HOST
                     */
                    agent.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
                    creds = new NTCredentials(username, password, AuthScope.ANY_HOST, domain);
                    agent.getCredentialsProvider()
                            .setCredentials(new AuthScope(AuthScope.ANY_HOST, port, realm), creds);
                } else {
                    /* Credentials only for Digest and Basic Authentication */
                    creds = new UsernamePasswordCredentials(username, password);
                    agent.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), creds);
                }
            }
            /* Customizing the priority Order */
            List schemes = authenticator.getAuthSchemes();
            if (schemes != null && schemes.size() > 0) {
                List authPrefs = new ArrayList(3);
                for (int i = 0; i < schemes.size(); i++) {
                    if (schemes.get(i) instanceof AuthPolicy) {
                        authPrefs.add(schemes.get(i));
                        continue;
                    }
                    String scheme = (String) schemes.get(i);
                    authPrefs.add(authenticator.getAuthPolicyPref(scheme));

                }
                agent.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authPrefs);
            }

        } else {
            throw new AxisFault("HttpTransportProperties.Authenticator class cast exception");
        }
    }

}

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;
}

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

protected AuthSchemeRegistry createAuthSchemeRegistry() {
    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 NegotiateSchemeFactory());
    return registry;
}

From source file:org.mitre.dsmiley.httpproxy.ProxyServlet.java

/**
 * Called from {@link #init(javax.servlet.ServletConfig)}. HttpClient offers
 * many opportunities for customization. By default, <a href=
 * "http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/SystemDefaultHttpClient.html">
 * SystemDefaultHttpClient</a> is used if available, otherwise it falls back
 * to://from  w w w  . jav  a 2  s .  c  o  m
 * 
 * <pre>
 * new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams)
 * </pre>
 * 
 * SystemDefaultHttpClient uses PoolingClientConnectionManager. In any case,
 * it should be thread-safe.
 */
protected HttpClient createHttpClient(HttpParams hcParams) {
    try {

        String negotiateURL = getConfigParam("negotiate.url");
        String negotiateSPN = getConfigParam("negotiate.spn");
        if (negotiateURL != null && negotiateSPN != null) {
            System.out.println("negotiate url:" + negotiateURL);
            System.out.println("negotiate spn:" + negotiateSPN);
            // initialize the Windows security Context to get the negotiate
            // client token
            IWindowsSecurityContext clientContext = null;
            IWindowsCredentialsHandle clientCredentials = null;
            clientContext = WindowsSecurityContextImpl.getCurrent(SECURITY_PACKAGE, negotiateSPN);
            clientCredentials = WindowsCredentialsHandleImpl.getCurrent(SECURITY_PACKAGE);
            clientCredentials.initialize();
            String username = WindowsAccountImpl.getCurrentUsername();
            System.out.println("credentials for user " + username + " get prepared");
            byte[] token = clientContext.getToken();
            // encode the token with Base64 to be able to add it to the http
            // header
            String clientToken = Base64.encodeBase64String(token);
            System.out.println("clientToken" + clientToken);
            // if there is only a negotiate url the rest of the
            // authorization is based on cookies
            // so we need to support them.
            CookieStore cookieStore = new BasicCookieStore();
            RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();
            HttpClientContext context = HttpClientContext.create();
            proxyContext = context;
            context.setCookieStore(cookieStore);
            HttpClient httpClient = HttpClients.custom().disableRedirectHandling()
                    .setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).build();

            // first we need to act as a normal browser to get a http 401
            // with negotiate header
            doActAsBrowser = true;
            HttpGet browserHttpGet = new HttpGet(negotiateURL);
            addBrowserHeader(browserHttpGet);
            HttpResponse rep = httpClient.execute(browserHttpGet, context);

            if (rep.getStatusLine().getStatusCode() == 401) {
                System.out.println("negotiate requested - sending negotiate client token");
                HttpGet negotiateHttpGet = new HttpGet(negotiateURL);
                addBrowserHeader(negotiateHttpGet);
                negotiateHttpGet.addHeader("Authorization", "Negotiate " + clientToken);
                HttpResponse response = httpClient.execute(negotiateHttpGet, context);
                System.out.println(
                        "http result code of negotiate request:" + response.getStatusLine().getStatusCode());
                // now the url needs to be called periodically to keep the
                // cookie and connection alive
                String refreshTimeString = getConfigParam("negotiate.refreshtime");
                long refreshTime = 1000000;
                if (refreshTimeString != null) {
                    refreshTime = Long.parseLong(refreshTimeString);
                }
                HttpClientRefreshThread thread = new HttpClientRefreshThread(refreshTime, negotiateURL);
                thread.start();
                List<org.apache.http.cookie.Cookie> cookies = context.getCookieStore().getCookies();
                cookieString = "";
                int size = cookies.size() - 1;
                for (int i = 0; i < cookies.size(); i++) {
                    cookieString += cookies.get(i).getName();
                    cookieString += "=";
                    cookieString += cookies.get(i).getValue();
                    if (i != size)
                        cookieString += "; ";
                }
            } else {
                System.out.println("No negotiate requested");
            }
        } else {
            if (!WinHttpClients.isWinAuthAvailable()) {
                System.out.println("Integrated Win auth is not supported!!!");
            } else {
                HttpClientBuilder builder = WinHttpClients.custom();
                Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                        .register(AuthSchemes.BASIC, new BasicSchemeFactory())
                        .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
                        .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
                        .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
                        .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build();
                builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
                String username = getConfigParam("user");
                String password = getConfigParam("password");
                String domain = getConfigParam("domain");
                String host = getConfigParam("host");
                if (username != null) {
                    NTCredentials cred = new NTCredentials(username, password, host, domain);
                    CredentialsProvider credsProvider = new WindowsCredentialsProvider(
                            new SystemDefaultCredentialsProvider());
                    credsProvider.setCredentials(AuthScope.ANY, cred);
                    builder.setDefaultCredentialsProvider(credsProvider);
                }
                builder.disableCookieManagement();
                builder.disableRedirectHandling();
                return builder.build();
            }

            // as of HttpComponents v4.2, this class is better since it uses
            // System
            // Properties:
            Class<?> clientClazz = Class.forName("org.apache.http.impl.client.SystemDefaultHttpClient");
            Constructor<?> constructor = clientClazz.getConstructor(HttpParams.class);
            return (HttpClient) constructor.newInstance(hcParams);
        }
    } catch (ClassNotFoundException e) {
        // no problem; use v4.1 below
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    // Fallback on using older client:
    return new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams);
}