Example usage for org.apache.http.auth.params AuthPNames TARGET_AUTH_PREF

List of usage examples for org.apache.http.auth.params AuthPNames TARGET_AUTH_PREF

Introduction

In this page you can find the example usage for org.apache.http.auth.params AuthPNames TARGET_AUTH_PREF.

Prototype

String TARGET_AUTH_PREF

To view the source code for org.apache.http.auth.params AuthPNames TARGET_AUTH_PREF.

Click Source Link

Document

Defines the order of preference for supported org.apache.http.auth.AuthScheme s when authenticating with the target host.

Usage

From source file:net.adamcin.httpsig.http.apache4.Http4Util.java

public static void enableAuth(final AbstractHttpClient client, final Keychain keychain, final KeyId keyId) {
    if (client == null) {
        throw new NullPointerException("client");
    }/*  w  w w . j  ava2 s .  co  m*/

    if (keychain == null) {
        throw new NullPointerException("keychain");
    }

    client.getAuthSchemes().register(Constants.SCHEME, new AuthSchemeFactory() {
        public AuthScheme newInstance(HttpParams params) {
            return new Http4SignatureAuthScheme();
        }
    });

    Signer signer = new Signer(keychain, keyId);
    client.getCredentialsProvider().setCredentials(AuthScope.ANY, new SignerCredentials(signer));
    client.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, Arrays.asList(Constants.SCHEME));

    HttpClientParams.setAuthenticating(client.getParams(), true);
}

From source file:at.pagu.soldockr.core.HttpSolrServerFactoryTest.java

@Test
public void testInitFactoryWithAuthentication() {
    HttpSolrServerFactory factory = new HttpSolrServerFactory(solrServer, "core",
            new UsernamePasswordCredentials("username", "password"), "BASIC");

    AbstractHttpClient solrHttpClient = (AbstractHttpClient) ((HttpSolrServer) factory.getSolrServer())
            .getHttpClient();//from w w  w.  j ava 2  s .c  o  m
    Assert.assertNotNull(solrHttpClient.getCredentialsProvider().getCredentials(AuthScope.ANY));
    Assert.assertNotNull(solrHttpClient.getParams().getParameter(AuthPNames.TARGET_AUTH_PREF));
    Assert.assertEquals("username", ((UsernamePasswordCredentials) solrHttpClient.getCredentialsProvider()
            .getCredentials(AuthScope.ANY)).getUserName());
    Assert.assertEquals("password", ((UsernamePasswordCredentials) solrHttpClient.getCredentialsProvider()
            .getCredentials(AuthScope.ANY)).getPassword());
}

From source file:at.pagu.soldockr.core.HttpSolrServerFactory.java

private void appendAuthentication(Credentials credentials, String authPolicy, SolrServer solrServer) {
    if (assertSolrServerInstance(solrServer)) {
        HttpSolrServer httpSolrServer = (HttpSolrServer) solrServer;

        if (credentials != null && StringUtils.isNotBlank(authPolicy)
                && assertHttpClientInstance(httpSolrServer.getHttpClient())) {
            AbstractHttpClient httpClient = (AbstractHttpClient) httpSolrServer.getHttpClient();
            httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
            httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, Arrays.asList(authPolicy));
        }//w ww  .j  a va  2s .c o  m
    }
}

From source file:org.springframework.data.solr.server.support.HttpSolrServerFactory.java

private void appendAuthentication(Credentials credentials, String authPolicy, SolrServer solrServer) {
    if (isHttpSolrServer(solrServer)) {
        HttpSolrServer httpSolrServer = (HttpSolrServer) solrServer;

        if (credentials != null && StringUtils.isNotBlank(authPolicy)
                && assertHttpClientInstance(httpSolrServer.getHttpClient())) {
            AbstractHttpClient httpClient = (AbstractHttpClient) httpSolrServer.getHttpClient();
            httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
            httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, Arrays.asList(authPolicy));
        }/*  w  w  w  .j  a  va  2s  .  com*/
    }
}

From source file:com.frank.search.solr.server.support.HttpSolrClientFactory.java

private void appendAuthentication(Credentials credentials, String authPolicy, SolrClient solrClient) {
    if (isHttpSolrClient(solrClient)) {
        HttpSolrClient httpSolrClient = (HttpSolrClient) solrClient;

        if (credentials != null && StringUtils.isNotBlank(authPolicy)
                && assertHttpClientInstance(httpSolrClient.getHttpClient())) {
            AbstractHttpClient httpClient = (AbstractHttpClient) httpSolrClient.getHttpClient();
            httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
            httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, Arrays.asList(authPolicy));
        }/*from   w w w.j  a  v a  2 s.c  om*/
    }
}

From source file:org.springframework.data.solr.HttpSolrClientFactoryTests.java

@Test
public void testInitFactoryWithAuthentication() {
    HttpSolrClientFactory factory = new HttpSolrClientFactory(solrClient, "core",
            new UsernamePasswordCredentials("username", "password"), "BASIC");

    AbstractHttpClient solrHttpClient = (AbstractHttpClient) ((HttpSolrClient) factory.getSolrClient())
            .getHttpClient();/*w  w  w.ja va2  s.  co  m*/
    Assert.assertNotNull(solrHttpClient.getCredentialsProvider().getCredentials(AuthScope.ANY));
    Assert.assertNotNull(solrHttpClient.getParams().getParameter(AuthPNames.TARGET_AUTH_PREF));
    Assert.assertEquals("username", ((UsernamePasswordCredentials) solrHttpClient.getCredentialsProvider()
            .getCredentials(AuthScope.ANY)).getUserName());
    Assert.assertEquals("password", ((UsernamePasswordCredentials) solrHttpClient.getCredentialsProvider()
            .getCredentials(AuthScope.ANY)).getPassword());
}

From source file:com.farmafene.commons.cas.URLAuthenticationHandler.java

/**
 * {@inheritDoc}/*from w w  w.  j  a  va 2 s.  c om*/
 * 
 * @see org.jasig.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler#authenticateUsernamePasswordInternal(org.jasig.cas.authentication.principal.UsernamePasswordCredentials)
 */
@Override
protected boolean authenticateUsernamePasswordInternal(UsernamePasswordCredentials credentials)
        throws AuthenticationException {
    long initTime = System.currentTimeMillis();
    boolean authenticateUsernamePasswordInternal = false;
    HttpContext context = new BasicHttpContext();
    HttpClientFactory f = new HttpClientFactory();
    f.setLoginURL(loginURL);
    f.setProxyHost(proxyHost);
    f.setProxyPort(proxyPort);
    DefaultHttpClient httpClient = f.getClient();
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    org.apache.http.auth.UsernamePasswordCredentials cred = new org.apache.http.auth.UsernamePasswordCredentials(
            credentials.getUsername(), credentials.getPassword());
    credsProvider.setCredentials(AuthScope.ANY, cred);
    List<String> n = new ArrayList<String>();
    n.add(AuthPolicy.BASIC);
    n.add(AuthPolicy.DIGEST);
    httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, n);
    context.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
    HttpGet httpGet = new HttpGet(loginURL);
    HttpResponse httpResponse = null;
    try {
        httpResponse = httpClient.execute(httpGet, context);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            authenticateUsernamePasswordInternal = true;
        }
    } catch (ClientProtocolException e) {
        logger.error("Error: ", e);
    } catch (IOException e) {
        logger.error("Error: ", e);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Total time: " + (System.currentTimeMillis() - initTime) + " ms, " + this);
    }
    return authenticateUsernamePasswordInternal;
}

From source file:com.intel.cosbench.api.httpauth.HttpAuth.java

@Override
public AuthContext login() {
    super.login();

    //        HttpHost host = new HttpHost();
    //        HttpHost targetHost = new HttpHost(host, port, protocol);

    URI uri;/*from  www  . j a v  a2s.c  om*/

    try {
        uri = new URI(auth_url);
    } catch (URISyntaxException use) {
        throw new AuthException(use);
    }

    HttpGet method = new HttpGet(auth_url);
    method.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);

    client.getCredentialsProvider().setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
            new UsernamePasswordCredentials(this.username, this.password));

    HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(AuthPNames.TARGET_AUTH_PREF,
            Arrays.asList(new String[] { AuthPolicy.BASIC, AuthPolicy.DIGEST }));

    HttpResponse response = null;

    try {
        dumpClientSettings();
        response = client.execute(method, localContext);

        dumpClientSettings();
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return createContext();
        }
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new AuthException(response.getStatusLine().getReasonPhrase());
        }
    } catch (SocketTimeoutException ste) {
        throw new AuthTimeoutException(ste);
    } catch (ConnectTimeoutException cte) {
        throw new AuthTimeoutException(cte);
    } catch (InterruptedIOException ie) {
        throw new AuthInterruptedException(ie);
    } catch (Exception e) {
        throw new AuthException(e);
    } finally {
        if (response != null)
            try {
                dumpResponse(response);
                EntityUtils.consume(response.getEntity());
            } catch (Exception ignore) {
                ignore.printStackTrace();
            }

        if (method != null)
            method.abort();
    }

    return createContext();
}

From source file:com.android.sdklib.internal.repository.UrlOpener.java

private static InputStream openWithHttpClient(String url, ITaskMonitor monitor)
        throws IOException, ClientProtocolException, CanceledByUserException {
    UserCredentials result = null;/*from ww  w .j a  v  a2  s.c  o m*/
    String realm = null;

    // use the simple one
    final DefaultHttpClient httpClient = new DefaultHttpClient();

    // create local execution context
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpget = new HttpGet(url);

    // retrieve local java configured network in case there is the need to
    // authenticate a proxy
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    // Set preference order for authentication options.
    // In particular, we don't add AuthPolicy.SPNEGO, which is given preference over NTLM in
    // servers that support both, as it is more secure. However, we don't seem to handle it
    // very well, so we leave it off the list.
    // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html for
    // more info.
    List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.BASIC);
    authpref.add(AuthPolicy.DIGEST);
    authpref.add(AuthPolicy.NTLM);
    httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);

    boolean trying = true;
    // loop while the response is being fetched
    while (trying) {
        // connect and get status code
        HttpResponse response = httpClient.execute(httpget, localContext);
        int statusCode = response.getStatusLine().getStatusCode();

        // check whether any authentication is required
        AuthState authenticationState = null;
        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            // Target host authentication required
            authenticationState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
        }
        if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            // Proxy authentication required
            authenticationState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
        }
        if (statusCode == HttpStatus.SC_OK) {
            // in case the status is OK and there is a realm and result,
            // cache it
            if (realm != null && result != null) {
                sRealmCache.put(realm, result);
            }
        }

        // there is the need for authentication
        if (authenticationState != null) {

            // get scope and realm
            AuthScope authScope = authenticationState.getAuthScope();

            // If the current realm is different from the last one it means
            // a pass was performed successfully to the last URL, therefore
            // cache the last realm
            if (realm != null && !realm.equals(authScope.getRealm())) {
                sRealmCache.put(realm, result);
            }

            realm = authScope.getRealm();

            // in case there is cache for this Realm, use it to authenticate
            if (sRealmCache.containsKey(realm)) {
                result = sRealmCache.get(realm);
            } else {
                // since there is no cache, request for login and password
                result = monitor.displayLoginCredentialsPrompt("Site Authentication",
                        "Please login to the following domain: " + realm
                                + "\n\nServer requiring authentication:\n" + authScope.getHost());
                if (result == null) {
                    throw new CanceledByUserException("User canceled login dialog.");
                }
            }

            // retrieve authentication data
            String user = result.getUserName();
            String password = result.getPassword();
            String workstation = result.getWorkstation();
            String domain = result.getDomain();

            // proceed in case there is indeed a user
            if (user != null && user.length() > 0) {
                Credentials credentials = new NTCredentials(user, password, workstation, domain);
                httpClient.getCredentialsProvider().setCredentials(authScope, credentials);
                trying = true;
            } else {
                trying = false;
            }
        } else {
            trying = false;
        }

        HttpEntity entity = response.getEntity();

        if (entity != null) {
            if (trying) {
                // in case another pass to the Http Client will be performed, close the entity.
                entity.getContent().close();
            } else {
                // since no pass to the Http Client is needed, retrieve the
                // entity's content.

                // Note: don't use something like a BufferedHttpEntity since it would consume
                // all content and store it in memory, resulting in an OutOfMemory exception
                // on a large download.

                return new FilterInputStream(entity.getContent()) {
                    @Override
                    public void close() throws IOException {
                        super.close();

                        // since Http Client is no longer needed, close it
                        httpClient.getConnectionManager().shutdown();
                    }
                };
            }
        }
    }

    // We get here if we did not succeed. Callers do not expect a null result.
    httpClient.getConnectionManager().shutdown();
    throw new FileNotFoundException(url);
}