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

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

Introduction

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

Prototype

String AUTH_SCHEME_PRIORITY

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

Click Source Link

Usage

From source file:org.apache.axis2.transport.http.impl.httpclient3.HTTPSenderImpl.java

protected void setAuthenticationInfo(HttpClient agent, MessageContext msgCtx, HostConfiguration config)
        throws AxisFault {
    HTTPAuthenticator authenticator;//from  w w w  .j  a va  2s  .  c om
    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;

            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);
                    authPrefs.add(authenticator.getAuthPolicyPref(scheme));

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

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

}

From source file:org.apache.camel.component.http.HttpEndpoint.java

/**
 * Factory method used by producers and consumers to create a new {@link HttpClient} instance
 *//*from   w w w. java 2 s  .  c  o m*/
public HttpClient createHttpClient() {
    ObjectHelper.notNull(clientParams, "clientParams");
    ObjectHelper.notNull(httpConnectionManager, "httpConnectionManager");

    HttpClient answer = new HttpClient(getClientParams());

    // configure http proxy from camelContext
    if (ObjectHelper.isNotEmpty(getCamelContext().getProperty("http.proxyHost"))
            && ObjectHelper.isNotEmpty(getCamelContext().getProperty("http.proxyPort"))) {
        String host = getCamelContext().getProperty("http.proxyHost");
        int port = Integer.parseInt(getCamelContext().getProperty("http.proxyPort"));
        LOG.debug(
                "CamelContext properties http.proxyHost and http.proxyPort detected. Using http proxy host: {} port: {}",
                host, port);
        answer.getHostConfiguration().setProxy(host, port);
    }

    if (proxyHost != null) {
        LOG.debug("Using proxy: {}:{}", proxyHost, proxyPort);
        answer.getHostConfiguration().setProxy(proxyHost, proxyPort);
    }

    if (authMethodPriority != null) {
        List<String> authPrefs = new ArrayList<String>();
        Iterator<?> it = getCamelContext().getTypeConverter().convertTo(Iterator.class, authMethodPriority);
        int i = 1;
        while (it.hasNext()) {
            Object value = it.next();
            AuthMethod auth = getCamelContext().getTypeConverter().convertTo(AuthMethod.class, value);
            if (auth == null) {
                throw new IllegalArgumentException(
                        "Unknown authMethod: " + value + " in authMethodPriority: " + authMethodPriority);
            }
            LOG.debug("Using authSchemePriority #{}: {}", i, auth);
            authPrefs.add(auth.name());
            i++;
        }
        if (!authPrefs.isEmpty()) {
            answer.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
        }
    }

    answer.setHttpConnectionManager(httpConnectionManager);
    HttpClientConfigurer configurer = getHttpClientConfigurer();
    if (configurer != null) {
        configurer.configureHttpClient(answer);
    }
    return answer;
}

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();/*  w w w  .j  a  v  a  2 s . c  om*/
            }
        }));

        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 {//  w ww.  j a  v a2s .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);/*from   w  w w . ja  v  a  2 s .c  o  m*/
    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);
    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);/*w  w  w .j av a  2s  .c  om*/
    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);
    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);/*w  w w . j  a v  a  2s .  c o  m*/
    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);
    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);//from   ww  w  .  ja  v  a  2  s  . co  m
    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);
    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 {/* www.  j ava2  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;
}

From source file:org.fao.geonet.lib.NetLib.java

/** Setup proxy for http client
  *//*from  w  w w  . ja  va  2 s.  c  o  m*/
public void setupProxy(SettingManager sm, HttpClient client) {
    boolean enabled = sm.getValueAsBool(ENABLED, false);
    String host = sm.getValue(HOST);
    String port = sm.getValue(PORT);
    String username = sm.getValue(USERNAME);
    String password = sm.getValue(PASSWORD);

    if (enabled) {
        if (!Lib.type.isInteger(port)) {
            Log.error(Geonet.GEONETWORK, "Proxy port is not an integer : " + port);
        } else {
            HostConfiguration config = client.getHostConfiguration();
            if (config == null)
                config = new HostConfiguration();
            config.setProxy(host, Integer.parseInt(port));
            client.setHostConfiguration(config);

            if (username.trim().length() != 0) {
                Credentials cred = new UsernamePasswordCredentials(username, password);
                AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);

                client.getState().setProxyCredentials(scope, cred);
            }
            List authPrefs = new ArrayList(2);
            authPrefs.add(AuthPolicy.DIGEST);
            authPrefs.add(AuthPolicy.BASIC);
            // This will exclude the NTLM authentication scheme
            client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
        }
    }
}