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: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;//from w  w w.  j ava  2  s .c  o  m

            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();//w  w  w . j  a v  a 2  s. c o  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 {/* ww  w  .j  ava2  s  .  c o m*/
        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);/*w w  w .  jav a2s .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  .jav a2s  .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);
    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);//from   w w  w .j  ava  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);
    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  w w w  . j av  a2  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"));
    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 {//  w  w  w.  j a  v a  2  s.  co 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.dataconservancy.dcs.access.server.DepositServiceImpl.java

private AbderaClient getClient(String endpoint, String user, String pass)
        throws MalformedURLException, URISyntaxException {

    AbderaClient client = new AbderaClient(abdera);

    AbderaClient.registerTrustManager(); // needed for SSL
    AbderaClient.registerScheme(AuthPolicy.BASIC, BasicScheme.class);

    client.setAuthenticationSchemePriority(AuthPolicy.BASIC);

    client.usePreemptiveAuthentication(false);
    client.addCredentials(endpoint, null, "basic", new UsernamePasswordCredentials(user, pass));
    //set credentials (for database & google oauth authentication)
    return client;

}

From source file:org.dataconservancy.dcs.access.server.MediciServiceImpl.java

private AbderaClient getClient(String endpoint, String user, String pass)
        throws MalformedURLException, URISyntaxException {

    AbderaClient client = new AbderaClient(abdera);

    AbderaClient.registerTrustManager(); // needed for SSL
    AbderaClient.registerScheme(AuthPolicy.BASIC, BasicScheme.class);
    client.setAuthenticationSchemePriority(AuthPolicy.BASIC);
    client.usePreemptiveAuthentication(false);
    client.addCredentials(endpoint, null, "basic", new UsernamePasswordCredentials(user, pass));
    return client;

}