Example usage for org.apache.commons.httpclient.auth AuthPolicy DIGEST

List of usage examples for org.apache.commons.httpclient.auth AuthPolicy DIGEST

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.auth AuthPolicy DIGEST.

Prototype

String DIGEST

To view the source code for org.apache.commons.httpclient.auth AuthPolicy DIGEST.

Click Source Link

Usage

From source file:org.abstracthorizon.proximity.storage.remote.CommonsHttpClientRemotePeer.java

/**
 * Gets the http client./*from  w ww . ja v  a  2 s .  co m*/
 * 
 * @return the http client
 */
public HttpClient getHttpClient() {
    if (httpClient == null) {
        logger.info("Creating CommonsHttpClient instance");
        httpRetryHandler = new DefaultHttpMethodRetryHandler(retrievalRetryCount, true);
        httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
        httpClient.getParams().setConnectionManagerTimeout(getConnectionTimeout());

        httpConfiguration = httpClient.getHostConfiguration();

        // BASIC and DIGEST auth only
        if (getUsername() != null) {

            List authPrefs = new ArrayList(2);
            authPrefs.add(AuthPolicy.DIGEST);
            authPrefs.add(AuthPolicy.BASIC);

            if (getNtlmDomain() != null) {
                // Using NTLM auth, adding it as first in policies
                authPrefs.add(0, AuthPolicy.NTLM);

                logger.info("... authentication setup for NTLM domain {}, username {}", getNtlmDomain(),
                        getUsername());
                httpConfiguration.setHost(getNtlmHost());

                httpClient.getState().setCredentials(AuthScope.ANY,
                        new NTCredentials(getUsername(), getPassword(), getNtlmHost(), getNtlmDomain()));
            } else {

                // Using Username/Pwd auth, will not add NTLM
                logger.info("... setting authentication setup for remote peer {}, with username {}",
                        getRemoteUrl(), getUsername());

                httpClient.getState().setCredentials(AuthScope.ANY,
                        new UsernamePasswordCredentials(getUsername(), getPassword()));

            }
            httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
        }

        if (getProxyHost() != null) {
            logger.info("... proxy setup with host {}", getProxyHost());
            httpConfiguration.setProxy(getProxyHost(), getProxyPort());

            if (getProxyUsername() != null) {

                List authPrefs = new ArrayList(2);
                authPrefs.add(AuthPolicy.DIGEST);
                authPrefs.add(AuthPolicy.BASIC);

                if (getProxyNtlmDomain() != null) {

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

                    if (getNtlmHost() != null) {
                        logger.warn("... CommonsHttpClient is unable to use NTLM auth scheme\n"
                                + " for BOTH server side and proxy side authentication!\n"
                                + " You MUST reconfigure server side auth and use BASIC/DIGEST scheme\n"
                                + " if you have to use NTLM proxy, since otherwise it will not work!\n"
                                + " *** SERVER SIDE AUTH OVERRIDDEN");
                    }
                    logger.info("... proxy authentication setup for NTLM domain {}, username {}",
                            getProxyNtlmDomain(), getProxyUsername());
                    httpConfiguration.setHost(getProxyNtlmHost());

                    httpClient.getState().setProxyCredentials(AuthScope.ANY, new NTCredentials(
                            getProxyUsername(), getProxyPassword(), getProxyNtlmHost(), getProxyNtlmDomain()));
                } else {

                    // Using Username/Pwd auth, will not add NTLM
                    logger.info("... proxy authentication setup for http proxy {}, username {}", getProxyHost(),
                            getProxyUsername());

                    httpClient.getState().setProxyCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(getProxyUsername(), getProxyPassword()));

                }
                httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
            }

        }
    }
    return httpClient;
}

From source file:org.anhonesteffort.flock.webdav.DavClient.java

protected void initClient() {
    HttpClientParams params = new HttpClientParams();
    List<String> authPrefs = new ArrayList<String>(2);

    authPrefs.add(AuthPolicy.DIGEST);
    authPrefs.add(AuthPolicy.BASIC);/*from  w ww  . j  ava2s .c  o  m*/
    params.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    params.setAuthenticationPreemptive(true);

    client = new HttpClient(params);
    hostConfiguration = client.getHostConfiguration();
    connectionManager = client.getHttpConnectionManager();

    hostConfiguration.setHost(davHost.getHost(), davHost.getPort(),
            Protocol.getProtocol(davHost.getProtocol()));

    Credentials credentials = new UsernamePasswordCredentials(davUsername, davPassword);
    client.getState().setCredentials(AuthScope.ANY, credentials);
}

From source file:org.apache.axis2.transport.http.AbstractHTTPSender.java

protected void setAuthenticationInfo(HttpClient agent, MessageContext msgCtx, HostConfiguration config)
        throws AxisFault {
    HttpTransportProperties.Authenticator authenticator;
    Object obj = msgCtx.getProperty(HTTPConstants.AUTHENTICATE);
    if (obj != null) {
        if (obj instanceof HttpTransportProperties.Authenticator) {
            authenticator = (HttpTransportProperties.Authenticator) 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;/*w w  w.  j a v a2 s  .  c om*/

            HttpState tmpHttpState = null;
            HttpState httpState = (HttpState) msgCtx.getProperty(HTTPConstants.CACHED_HTTP_STATE);
            if (httpState != null) {
                tmpHttpState = httpState;
            } else {
                tmpHttpState = agent.getState();
            }

            agent.getParams().setAuthenticationPreemptive(authenticator.getPreemptiveAuthentication());

            if (host != null) {
                if (domain != null) {
                    /*Credentials for NTLM Authentication*/
                    creds = new NTCredentials(username, password, host, domain);
                } else {
                    /*Credentials for Digest and Basic Authentication*/
                    creds = new UsernamePasswordCredentials(username, password);
                }
                tmpHttpState.setCredentials(new AuthScope(host, port, realm), creds);
            } else {
                if (domain != null) {
                    /*Credentials for NTLM Authentication when host is ANY_HOST*/
                    creds = new NTCredentials(username, password, AuthScope.ANY_HOST, domain);
                    tmpHttpState.setCredentials(new AuthScope(AuthScope.ANY_HOST, port, realm), creds);
                } else {
                    /*Credentials only for Digest and Basic Authentication*/
                    creds = new UsernamePasswordCredentials(username, password);
                    tmpHttpState.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);
                    if (HttpTransportProperties.Authenticator.BASIC.equals(scheme)) {
                        authPrefs.add(AuthPolicy.BASIC);
                    } else if (HttpTransportProperties.Authenticator.NTLM.equals(scheme)) {
                        authPrefs.add(AuthPolicy.NTLM);
                    } else if (HttpTransportProperties.Authenticator.DIGEST.equals(scheme)) {
                        authPrefs.add(AuthPolicy.DIGEST);
                    }
                }
                agent.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
            }

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

}

From source file:org.apache.ivy.util.url.HttpClientHandler.java

private HttpClient getClient() {
    if (httpClient == null) {
        final MultiThreadedHttpConnectionManager connManager = new MultiThreadedHttpConnectionManager();
        httpClient = new HttpClient(connManager);

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            public void run() {
                connManager.shutdown();/* ww w.  ja  v a  2s.  co  m*/
            }
        }));

        List authPrefs = new ArrayList(3);
        authPrefs.add(AuthPolicy.DIGEST);
        authPrefs.add(AuthPolicy.BASIC);
        authPrefs.add(AuthPolicy.NTLM); // put it at the end to give less priority (IVY-213)
        httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

        if (useProxy()) {
            httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort);
            if (useProxyAuthentication()) {
                httpClient.getState().setProxyCredentials(
                        new AuthScope(proxyHost, proxyPort, AuthScope.ANY_REALM),
                        createCredentials(proxyUserName, proxyPasswd));
            }
        }

        // user-agent
        httpClient.getParams().setParameter(HttpMethodParams.USER_AGENT, getUserAgent());

        // authentication
        httpClient.getParams().setParameter(CredentialsProvider.PROVIDER, new IvyCredentialsProvider());
    }

    return httpClient;
}

From source file:org.apache.wookie.proxy.ProxyClient.java

private String executeMethod(HttpMethod method, Configuration properties)
        throws Exception, AuthenticationException {
    // Execute the method.
    try {//from  ww  w. j  a  v  a 2 s .  c  om
        HttpClient client = new HttpClient();

        // set the clients proxy values if needed
        ConnectionsPrefsManager.setProxySettings(client, properties);

        if (fUseProxyAuthentication) {
            if (fBase64Auth != null) {
                method.setRequestHeader("Authorization", fBase64Auth);
            } else {
                List<String> authPrefs = new ArrayList<String>(2);
                authPrefs.add(AuthPolicy.DIGEST);
                authPrefs.add(AuthPolicy.BASIC);
                client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
                // send the basic authentication response even before the server gives an unauthorized response
                client.getParams().setAuthenticationPreemptive(true);
                // Pass our credentials to HttpClient
                client.getState().setCredentials(
                        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
                        new UsernamePasswordCredentials(fProxyUsername, fProxyPassword));
            }
        }

        // Add user language to http request in order to notify server of user's language
        Locale locale = Locale.getDefault();

        method.setRequestHeader("Accept-Language", locale.getLanguage()); //$NON-NLS-1$
        method.removeRequestHeader("Content-Type");
        //method.setRequestHeader("Content-Type","application/json");
        //method.setRequestHeader("Referer", "");
        //method.removeRequestHeader("Referer");
        method.setRequestHeader("Accept", "*/*");

        int statusCode = client.executeMethod(method);

        //System.out.println("response="+method.getResponseBodyAsString());
        //System.out.println("method="+method.toString());
        //System.out.println("response="+method.getResponseBodyAsStream());

        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
            Header hType = method.getResponseHeader("Content-Type");
            if (hType != null) {
                fContentType = hType.getValue();
            }
            // for now we are only expecting Strings
            //return method.getResponseBodyAsString();
            return readFully(new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8"));
        } else if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED
                || statusCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new AuthenticationException("Authentication failed:" + method.getStatusLine() + ' '
                    + method.getURI() + ' ' + method.getStatusText());
        } else {
            throw new Exception("Method failed: " + method.getStatusLine() + ' ' + method.getURI() + ' ' //$NON-NLS-1$
                    + method.getStatusText());
        }
    } catch (IOException e) {
        throw e;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:org.apache.wookie.tests.functional.ProxyTest.java

@Test
public void postWithOnlyQueryStringParameters() throws Exception {
    HttpClient client = new HttpClient();
    List<String> authPrefs = new ArrayList<String>(2);
    authPrefs.add(AuthPolicy.DIGEST);
    authPrefs.add(AuthPolicy.BASIC);/*ww  w.  j av  a 2  s. c o m*/
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    // send the basic authentication response even before the server gives an unauthorized response
    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
            new UsernamePasswordCredentials("java", "java"));
    PostMethod req;
    req = new PostMethod(PROXY_URL + "?instanceid_key=" + instance_id_key + "&url=" + PROTECTED_SITE_URL);
    client.executeMethod(req);
    int code = req.getStatusCode();
    req.releaseConnection();
    assertEquals(200, code);
}

From source file:org.apache.wookie.tests.functional.ProxyTest.java

@Test
public void postWithMixedQueryAndParameters() throws Exception {
    HttpClient client = new HttpClient();
    List<String> authPrefs = new ArrayList<String>(2);
    authPrefs.add(AuthPolicy.DIGEST);
    authPrefs.add(AuthPolicy.BASIC);/*from w ww  . j av  a  2 s. co m*/
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    // send the basic authentication response even before the server gives an unauthorized response
    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
            new UsernamePasswordCredentials("java", "java"));
    PostMethod req;
    req = new PostMethod(PROXY_URL + "?instanceid_key=" + instance_id_key);
    req.addParameter("url", PROTECTED_SITE_URL);
    client.executeMethod(req);
    int code = req.getStatusCode();
    req.releaseConnection();
    assertEquals(200, code);
}

From source file:org.apache.wookie.tests.functional.ProxyTest.java

@Test
public void postWithOnlyParameters() throws Exception {
    HttpClient client = new HttpClient();
    List<String> authPrefs = new ArrayList<String>(2);
    authPrefs.add(AuthPolicy.DIGEST);
    authPrefs.add(AuthPolicy.BASIC);/*from   w w  w  . j a  va  2  s .co  m*/
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    // send the basic authentication response even before the server gives an unauthorized response
    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
            new UsernamePasswordCredentials("java", "java"));
    PostMethod req;
    req = new PostMethod(PROXY_URL);
    req.addParameter("url", PROTECTED_SITE_URL);
    req.addParameter("instanceid_key", instance_id_key);
    client.executeMethod(req);
    int code = req.getStatusCode();
    req.releaseConnection();
    assertEquals(200, code);
}

From source file:org.apache.wookie.tests.functional.ProxyTest.java

@Test
public void getProtectedSiteWithBasicAuth() throws Exception {
    HttpClient client = new HttpClient();
    List<String> authPrefs = new ArrayList<String>(2);
    authPrefs.add(AuthPolicy.DIGEST);
    authPrefs.add(AuthPolicy.BASIC);//from w  w w  .  j a  v a  2s  .c  o m
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    // send the basic authentication response even before the server gives an unauthorized response
    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
            new UsernamePasswordCredentials("java", "java"));
    HttpMethod req;
    req = new GetMethod(PROXY_URL + "?instanceid_key=" + instance_id_key + "&url=" + PROTECTED_SITE_URL);
    client.executeMethod(req);
    int code = req.getStatusCode();
    req.releaseConnection();
    assertEquals(200, code);
}

From source file:org.archive.modules.credential.HttpAuthenticationCredential.java

@Override
public boolean populate(CrawlURI curi, HttpClient http, HttpMethod method,
        Map<String, String> httpAuthChallenges) {
    boolean result = false;

    AuthChallengeProcessor authChallengeProcessor = new AuthChallengeProcessor(http.getParams());
    try {// ww  w.  jav  a  2 s  .c  o m
        AuthScheme authScheme = authChallengeProcessor.processChallenge(method.getHostAuthState(),
                httpAuthChallenges);
        method.getHostAuthState().setAuthScheme(authScheme);
    } catch (MalformedChallengeException e) {
        return result;
    } catch (AuthenticationException e) {
        return result;
    }

    // Always add the credential to HttpState. Doing this because no way of
    // removing the credential once added AND there is a bug in the
    // credentials management system in that it always sets URI root to
    // null: it means the key used to find a credential is NOT realm + root
    // URI but just the realm. Unless I set it everytime, there is
    // possibility that as this thread progresses, it might come across a
    // realm already loaded but the login and password are from another
    // server. We'll get a failed authentication that'd be difficult to
    // explain.
    //
    // Have to make a UsernamePasswordCredentials. The httpclient auth code
    // does an instanceof down in its guts.
    UsernamePasswordCredentials upc = null;
    try {
        upc = new UsernamePasswordCredentials(getLogin(), getPassword());
        http.getState().setCredentials(
                new AuthScope(curi.getUURI().getHost(), curi.getUURI().getPort(), getRealm()), upc);
        logger.fine("Credentials for realm " + getRealm() + " for CrawlURI " + curi.toString()
                + " added to request: " + result);

        http.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY,
                Arrays.asList(AuthPolicy.DIGEST, AuthPolicy.BASIC));

        result = true;
    } catch (URIException e) {
        logger.severe("Failed to parse host from " + curi + ": " + e.getMessage());
    }

    return result;
}