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

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

Introduction

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

Prototype

String BASIC

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

Click Source Link

Usage

From source file:AlternateAuthenticationExample.java

public static void main(String[] args) throws Exception {
    HttpClient client = new HttpClient();
    client.getState().setCredentials(new AuthScope("myhost", 80, "myrealm"),
            new UsernamePasswordCredentials("username", "password"));
    // Suppose the site supports several authetication schemes: NTLM and Basic
    // Basic authetication is considered inherently insecure. Hence, NTLM authentication
    // is used per default

    // This is to make HttpClient pick the Basic authentication scheme over NTLM & Digest
    List authPrefs = new ArrayList(3);
    authPrefs.add(AuthPolicy.BASIC);
    authPrefs.add(AuthPolicy.NTLM);/* w  ww.  j  a v a2  s  .  c o  m*/
    authPrefs.add(AuthPolicy.DIGEST);
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

    GetMethod httpget = new GetMethod("http://myhost/protected/auth-required.html");

    try {
        int status = client.executeMethod(httpget);
        // print the status and response
        System.out.println(httpget.getStatusLine());
        System.out.println(httpget.getResponseBodyAsString());
    } finally {
        // release any connection resources used by the method
        httpget.releaseConnection();
    }
}

From source file:ir.keloud.android.lib.common.KeloudBasicCredentials.java

@Override
public void applyTo(KeloudClient client) {
    List<String> authPrefs = new ArrayList<String>(1);
    authPrefs.add(AuthPolicy.BASIC);
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(mUsername, mPassword));
}

From source file:com.cerema.cloud2.lib.common.OwnCloudBasicCredentials.java

@Override
public void applyTo(OwnCloudClient client) {
    List<String> authPrefs = new ArrayList<String>(1);
    authPrefs.add(AuthPolicy.BASIC);
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(mUsername, mPassword));
}

From source file:com.owncloud.android.oc_framework.network.webdav.WebdavClient.java

public void setBasicCredentials(String username, String password) {
    List<String> authPrefs = new ArrayList<String>(1);
    authPrefs.add(AuthPolicy.BASIC);
    getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

    getParams().setAuthenticationPreemptive(true);
    mCredentials = new UsernamePasswordCredentials(username, password);
    getState().setCredentials(AuthScope.ANY, mCredentials);
    mSsoSessionCookie = null;//w  w w.j a  v  a  2s .  c o  m
}

From source file:eu.alefzero.webdav.WebdavClient.java

public void setBasicCredentials(String username, String password) {
    List<String> authPrefs = new ArrayList<String>(1);
    authPrefs.add(AuthPolicy.BASIC);
    getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

    getParams().setAuthenticationPreemptive(true);
    mCredentials = new UsernamePasswordCredentials(username, password);
    getState().setCredentials(AuthScope.ANY, mCredentials);
    mSsoSessionCookie = null;//w w  w.  java  2 s  .c om
    mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD;
}

From source file:jeeves.utils.XmlRequest.java

public XmlRequest(String host, int port, String protocol) {
    this.host = host;
    this.port = port;
    this.protocol = protocol;

    setMethod(Method.GET);//ww w.ja  va  2  s  .  c  o  m
    state.addCookie(cookie);
    client.setState(state);
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    client.setHostConfiguration(config);
    List<String> authPrefs = new ArrayList<String>(2);
    authPrefs.add(AuthPolicy.DIGEST);
    authPrefs.add(AuthPolicy.BASIC);
    // This will exclude the NTLM authentication scheme 
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
}

From source file:com.mirth.connect.connectors.http.HttpMessageDispatcher.java

private void submitHttpRequest(String address, MessageObject mo) throws Exception {
    HttpMethod httpMethod = null;/*from  w ww . ja  v a  2  s .c  om*/

    try {
        httpMethod = buildHttpRequest(replacer.replaceValues(address, mo), mo);

        // authentication

        if (connector.isDispatcherUseAuthentication()) {
            List<String> authenticationPreferences = new ArrayList<String>();

            if ("Digest".equalsIgnoreCase(connector.getDispatcherAuthenticationType())) {
                authenticationPreferences.add(AuthPolicy.DIGEST);
                logger.debug("using Digest authentication");
            } else {
                authenticationPreferences.add(AuthPolicy.BASIC);
                logger.debug("using Basic authentication");
            }

            client.getParams().setAuthenticationPreemptive(true);
            client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authenticationPreferences);
            Credentials credentials = new UsernamePasswordCredentials(
                    replacer.replaceValues(connector.getDispatcherUsername(), mo),
                    replacer.replaceValues(connector.getDispatcherPassword(), mo));
            client.getState().setCredentials(
                    new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), credentials);
            logger.debug("using authentication with credentials: " + credentials);
        }

        client.getParams().setSoTimeout(
                NumberUtils.toInt(replacer.replaceValues(connector.getDispatcherSocketTimeout()), 30000));

        // execute the method
        logger.debug(
                "executing method: type=" + httpMethod.getName() + ", uri=" + httpMethod.getURI().toString());
        int statusCode = client.executeMethod(httpMethod);
        logger.debug("received status code: " + statusCode);

        String response = null;

        if (connector.isDispatcherIncludeHeadersInResponse()) {
            HttpMessageConverter converter = new HttpMessageConverter();
            response = converter.httpResponseToXml(httpMethod.getStatusLine().toString(),
                    httpMethod.getResponseHeaders(), httpMethod.getResponseBodyAsString());
        } else {
            response = httpMethod.getResponseBodyAsString();
        }

        if (statusCode < HttpStatus.SC_BAD_REQUEST) {
            messageObjectController.setSuccess(mo, response, null);

            // send to reply channel
            if ((connector.getDispatcherReplyChannelId() != null)
                    && !connector.getDispatcherReplyChannelId().equals("sink")) {
                new VMRouter().routeMessageByChannelId(connector.getDispatcherReplyChannelId(), response, true);
            }
        } else {
            alertController.sendAlerts(connector.getChannelId(), Constants.ERROR_404,
                    "Received error response from HTTP server.", null);
            messageObjectController.setError(mo, Constants.ERROR_404, response, null, null);
        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:com.liferay.portal.util.HttpImpl.java

public HttpImpl() {

    // Mimic behavior found in
    // http://java.sun.com/j2se/1.5.0/docs/guide/net/properties.html

    if (Validator.isNotNull(_NON_PROXY_HOSTS)) {
        String nonProxyHostsRegEx = _NON_PROXY_HOSTS;

        nonProxyHostsRegEx = nonProxyHostsRegEx.replaceAll("\\.", "\\\\.");
        nonProxyHostsRegEx = nonProxyHostsRegEx.replaceAll("\\*", ".*?");
        nonProxyHostsRegEx = nonProxyHostsRegEx.replaceAll("\\|", ")|(");

        nonProxyHostsRegEx = "(" + nonProxyHostsRegEx + ")";

        _nonProxyHostsPattern = Pattern.compile(nonProxyHostsRegEx);
    }// w w  w.  j a va2 s .c  o  m

    MultiThreadedHttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager();

    HttpConnectionManagerParams httpConnectionManagerParams = httpConnectionManager.getParams();

    httpConnectionManagerParams.setConnectionTimeout(_TIMEOUT);
    httpConnectionManagerParams.setDefaultMaxConnectionsPerHost(new Integer(_MAX_CONNECTIONS_PER_HOST));
    httpConnectionManagerParams.setMaxTotalConnections(new Integer(_MAX_TOTAL_CONNECTIONS));
    httpConnectionManagerParams.setSoTimeout(_TIMEOUT);

    _httpClient.setHttpConnectionManager(httpConnectionManager);
    _proxyHttpClient.setHttpConnectionManager(httpConnectionManager);

    if (hasProxyConfig() && Validator.isNotNull(_PROXY_USERNAME)) {
        List<String> authPrefs = new ArrayList<String>();

        if (_PROXY_AUTH_TYPE.equals("username-password")) {
            _proxyCredentials = new UsernamePasswordCredentials(_PROXY_USERNAME, _PROXY_PASSWORD);

            authPrefs.add(AuthPolicy.BASIC);
            authPrefs.add(AuthPolicy.DIGEST);
            authPrefs.add(AuthPolicy.NTLM);
        } else if (_PROXY_AUTH_TYPE.equals("ntlm")) {
            _proxyCredentials = new NTCredentials(_PROXY_USERNAME, _PROXY_PASSWORD, _PROXY_NTLM_HOST,
                    _PROXY_NTLM_DOMAIN);

            authPrefs.add(AuthPolicy.NTLM);
            authPrefs.add(AuthPolicy.BASIC);
            authPrefs.add(AuthPolicy.DIGEST);
        }

        HttpClientParams httpClientParams = _proxyHttpClient.getParams();

        httpClientParams.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    }
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Update http client configuration (proxy)
 *
 * @param httpClient current Http client
 * @param url        target url//from   w  w  w .j  a  v a 2  s. co  m
 * @throws DavMailException on error
 */
public static void configureClient(HttpClient httpClient, String url) throws DavMailException {
    setClientHost(httpClient, url);

    /*if (Settings.getBooleanProperty("davmail.enableKerberos", false)) {
    AuthPolicy.registerAuthScheme("Negotiate", NegotiateScheme.class);
    ArrayList<String> authPrefs = new ArrayList<String>();
    authPrefs.add("Negotiate");
    httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    } else */if (!needNTLM) {
        ArrayList<String> authPrefs = new ArrayList<String>();
        authPrefs.add(AuthPolicy.DIGEST);
        authPrefs.add(AuthPolicy.BASIC);
        // exclude NTLM authentication scheme
        httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    }

    boolean enableProxy = Settings.getBooleanProperty("davmail.enableProxy");
    boolean useSystemProxies = Settings.getBooleanProperty("davmail.useSystemProxies", Boolean.FALSE);
    String proxyHost = null;
    int proxyPort = 0;
    String proxyUser = null;
    String proxyPassword = null;

    try {
        java.net.URI uri = new java.net.URI(url);
        if (isNoProxyFor(uri)) {
            LOGGER.debug("no proxy for " + uri.getHost());
        } else if (useSystemProxies) {
            // get proxy for url from system settings
            System.setProperty("java.net.useSystemProxies", "true");
            List<Proxy> proxyList = getProxyForURI(uri);
            if (!proxyList.isEmpty() && proxyList.get(0).address() != null) {
                InetSocketAddress inetSocketAddress = (InetSocketAddress) proxyList.get(0).address();
                proxyHost = inetSocketAddress.getHostName();
                proxyPort = inetSocketAddress.getPort();

                // we may still need authentication credentials
                proxyUser = Settings.getProperty("davmail.proxyUser");
                proxyPassword = Settings.getProperty("davmail.proxyPassword");
            }
        } else if (enableProxy) {
            proxyHost = Settings.getProperty("davmail.proxyHost");
            proxyPort = Settings.getIntProperty("davmail.proxyPort");
            proxyUser = Settings.getProperty("davmail.proxyUser");
            proxyPassword = Settings.getProperty("davmail.proxyPassword");
        }
    } catch (URISyntaxException e) {
        throw new DavMailException("LOG_INVALID_URL", url);
    }

    // configure proxy
    if (proxyHost != null && proxyHost.length() > 0) {
        httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort);
        if (proxyUser != null && proxyUser.length() > 0) {

            AuthScope authScope = new AuthScope(proxyHost, proxyPort, AuthScope.ANY_REALM);

            // detect ntlm authentication (windows domain name in user name)
            int backslashindex = proxyUser.indexOf('\\');
            if (backslashindex > 0) {
                httpClient.getState().setProxyCredentials(authScope,
                        new NTCredentials(proxyUser.substring(backslashindex + 1), proxyPassword, "UNKNOWN",
                                proxyUser.substring(0, backslashindex)));
            } else {
                httpClient.getState().setProxyCredentials(authScope,
                        new NTCredentials(proxyUser, proxyPassword, "UNKNOWN", ""));
            }
        }
    }

}

From source file:fr.jayasoft.ivy.url.HttpClientHandler.java

private HttpClient getClient(URL url) {
    HttpClient client = new HttpClient();

    List authPrefs = new ArrayList(2);
    authPrefs.add(AuthPolicy.DIGEST);// www  . j  a  v  a  2 s. c  om
    authPrefs.add(AuthPolicy.BASIC);
    // Exclude the NTLM authentication scheme because it is not supported by this class
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

    if (useProxy()) {
        client.getHostConfiguration().setProxy(_proxyHost, _proxyPort);
        if (useProxyAuthentication()) {
            client.getState().setProxyCredentials(_proxyRealm, _proxyHost,
                    new UsernamePasswordCredentials(_proxyUserName, _proxyPasswd));
        }
    }
    Credentials c = getCredentials(url);
    if (c != null) {
        Message.debug("found credentials for " + url + ": " + c);
        client.getState().setCredentials(c.getRealm(), c.getHost(),
                new UsernamePasswordCredentials(c.getUserName(), c.getPasswd()));
    }
    return client;
}