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:org.eclipse.mylyn.commons.http.HttpUtil.java

public static HttpContext getHttpContext(AbstractHttpClient client, AbstractWebLocation location,
        HttpContext previousContext, IProgressMonitor progressMonitor) {

    Assert.isNotNull(client);//from  ww  w. ja  va2s  .co m
    Assert.isNotNull(location);

    String url = location.getUrl();
    String host = getHost(url);
    int port = getPort(url);

    configureHttpClientConnectionManager(client);

    HttpContext context = previousContext;
    if (context == null) {
        context = new BasicHttpContext();
    }
    configureHttpClientProxy(client, context, location);

    AuthenticationCredentials authCreds = location.getCredentials(AuthenticationType.HTTP);
    if (authCreds != null) {
        AuthScope authScope = new AuthScope(host, port, AuthScope.ANY_REALM);
        Credentials credentials = getHttpClientCredentials(authCreds, host);

        if (credentials instanceof NTCredentials) {
            List<String> authpref = new ArrayList<String>();
            authpref.add(AuthPolicy.NTLM);
            authpref.add(AuthPolicy.BASIC);
            authpref.add(AuthPolicy.DIGEST);
            client.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);
        } else {
            List<String> authpref = new ArrayList<String>();
            authpref.add(AuthPolicy.BASIC);
            authpref.add(AuthPolicy.DIGEST);
            authpref.add(AuthPolicy.NTLM);
            client.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);
        }
        client.getCredentialsProvider().setCredentials(authScope, credentials);
    }

    if (isRepositoryHttps(url)) {
        Scheme sch = new Scheme("https", HTTPS_PORT, sslSocketFactory); //$NON-NLS-1$
        client.getConnectionManager().getSchemeRegistry().register(sch);
    } else {
        Scheme sch = new Scheme("http", HTTP_PORT, socketFactory); //$NON-NLS-1$
        client.getConnectionManager().getSchemeRegistry().register(sch);
    }

    return context;

}

From source file:com.android.tools.idea.sdk.remote.internal.UrlOpener.java

@NonNull
private static Pair<InputStream, HttpResponse> openWithHttpClient(@NonNull String url,
        @NonNull ITaskMonitor monitor, Header[] inHeaders) throws IOException, CanceledByUserException {
    UserCredentials result = null;// w w  w. j a  v  a 2s . co m
    String realm = null;

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, sConnectionTimeoutMs);
    HttpConnectionParams.setSoTimeout(params, sSocketTimeoutMs);

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

    // create local execution context
    HttpContext localContext = new BasicHttpContext();
    final HttpGet httpGet = new HttpGet(url);
    if (inHeaders != null) {
        for (Header header : inHeaders) {
            httpGet.addHeader(header);
        }
    }

    // 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);

    if (DEBUG) {
        try {
            URI uri = new URI(url);
            ProxySelector sel = routePlanner.getProxySelector();
            if (sel != null && uri.getScheme().startsWith("httP")) { //$NON-NLS-1$
                List<Proxy> list = sel.select(uri);
                System.out.printf("SdkLib.UrlOpener:\n  Connect to: %s\n  Proxy List: %s\n", //$NON-NLS-1$
                        url, list == null ? "(null)" : Arrays.toString(list.toArray()));//$NON-NLS-1$
            }
        } catch (Exception e) {
            System.out.printf("SdkLib.UrlOpener: Failed to get proxy info for %s: %s\n", //$NON-NLS-1$
                    url, e.toString());
        }
    }

    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();

        if (DEBUG) {
            System.out.printf("  Status: %d\n", statusCode); //$NON-NLS-1$
        }

        // 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 || statusCode == HttpStatus.SC_NOT_MODIFIED) {
            // 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.
                InputStream is = new FilterInputStream(entity.getContent()) {
                    @Override
                    public void close() throws IOException {
                        // Since Http Client is no longer needed, close it.

                        // Bug #21167: we need to tell http client to shutdown
                        // first, otherwise the super.close() would continue
                        // downloading and not return till complete.

                        httpClient.getConnectionManager().shutdown();
                        super.close();
                    }
                };

                HttpResponse outResponse = new BasicHttpResponse(response.getStatusLine());
                outResponse.setHeaders(response.getAllHeaders());
                outResponse.setLocale(response.getLocale());

                return Pair.of(is, outResponse);
            }
        } else if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
            // It's ok to not have an entity (e.g. nothing to download) for a 304
            HttpResponse outResponse = new BasicHttpResponse(response.getStatusLine());
            outResponse.setHeaders(response.getAllHeaders());
            outResponse.setLocale(response.getLocale());

            return Pair.of(null, outResponse);
        }
    }

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

From source file:org.hyperic.plugin.vrealize.automation.DiscoveryVRAIaasWeb.java

private static String getVCO(ConfigResponse config) {
    String vcoFNQ = null;/*from www  .  j  av a 2s .  c o m*/
    String xml = null;

    String user = config.getValue("iaas.http.user", "");
    String pass = config.getValue("iaas.http.pass", "");
    String domain = config.getValue("iaas.http.domain", "");

    try {
        AgentKeystoreConfig ksCFG = new AgentKeystoreConfig();
        HQHttpClient client = new HQHttpClient(ksCFG, new HttpConfig(5000, 5000, null, 0),
                ksCFG.isAcceptUnverifiedCert());

        List<String> authpref = new ArrayList<String>();
        authpref.add(AuthPolicy.NTLM);
        authpref.add(AuthPolicy.BASIC);
        client.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);

        client.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthPolicy.NTLM),
                new NTCredentials(user, pass, "localhost", domain));

        HttpGet get = new HttpGet(
                "https://localhost/Repository/Data/ManagementModelEntities.svc/ManagementEndpoints");
        HttpResponse response = client.execute(get);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            xml = readInputString(response.getEntity().getContent());
        } else {
            log.debug("[getVCOx] GET failed: " + response.getStatusLine().getReasonPhrase());
        }
    } catch (IOException ex) {
        log.debug("[getVCOx] " + ex, ex);
    }

    if (xml != null) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = (Document) builder.parse(new ByteArrayInputStream(xml.getBytes()));

            log.debug("[getVCOx] xml:" + xml);

            XPathFactory xFactory = XPathFactory.newInstance();
            XPath xpath = xFactory.newXPath();

            String xPath = "//properties[InterfaceType[text()='vCO']]/ManagementEndpointName/text()";

            log.debug("[getVCOx] evaluating XPath:" + xPath);

            vcoFNQ = xpath.evaluate(xPath, doc);

            log.debug("[getVCOx] vcoFNQ:" + vcoFNQ);

        } catch (Exception ex) {
            log.debug("[getVCOx] " + ex, ex);
        }
    }

    return VRAUtils.getFqdn(vcoFNQ);
}

From source file:org.callimachusproject.client.HttpClientFactoryTest.java

@Test
public void testAuthentication() throws Exception {
    HttpGet get = new HttpGet("http://example.com/protected");
    HttpContext localContext = new BasicHttpContext();
    List<String> authpref = Collections.singletonList(AuthPolicy.BASIC);
    AuthScope scope = new AuthScope("example.com", -1);
    UsernamePasswordCredentials cred = new UsernamePasswordCredentials("Aladdin", "open sesame");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(scope, cred);
    localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
    get.getParams().setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, true);
    get.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);
    BasicHttpResponse unauth = new BasicHttpResponse(_401);
    unauth.setHeader("WWW-Authenticate", "Basic realm=\"insert realm\"");
    responses.add(unauth);/*from  w  w w.  j  ava  2s  . c om*/
    responses.add(new BasicHttpResponse(_200));
    client.execute(get, new ResponseHandler<Void>() {
        public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode());
            assertContains("Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", asString(response.getEntity()));
            return null;
        }
    }, localContext);
}

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

protected void setAuthenticationInfo(AbstractHttpClient agent, MessageContext msgCtx) throws AxisFault {
    HTTPAuthenticator authenticator;//from w  ww  .  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;

            // TODO : Set preemptive authentication, but its not recommended in HC 4

            if (host != null) {
                if (domain != null) {
                    /* Credentials for NTLM Authentication */
                    agent.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
                    creds = new NTCredentials(username, password, host, domain);
                } else {
                    /* Credentials for Digest and Basic Authentication */
                    creds = new UsernamePasswordCredentials(username, password);
                }
                agent.getCredentialsProvider().setCredentials(new AuthScope(host, port, realm), creds);
            } else {
                if (domain != null) {
                    /*
                     * Credentials for NTLM Authentication when host is
                     * ANY_HOST
                     */
                    agent.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
                    creds = new NTCredentials(username, password, AuthScope.ANY_HOST, domain);
                    agent.getCredentialsProvider()
                            .setCredentials(new AuthScope(AuthScope.ANY_HOST, port, realm), creds);
                } else {
                    /* Credentials only for Digest and Basic Authentication */
                    creds = new UsernamePasswordCredentials(username, password);
                    agent.getCredentialsProvider().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(AuthPNames.TARGET_AUTH_PREF, authPrefs);
            }

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

}

From source file:org.eclipse.ecf.provider.filetransfer.httpclient4.HttpClientRetrieveFileTransfer.java

private void registerSchemes(ISocketEventSource source, ISocketListener socketListener) {
    SchemeRegistry schemeRegistry = this.httpClient.getConnectionManager().getSchemeRegistry();

    Scheme http = new Scheme(HttpClientRetrieveFileTransfer.HTTP, HTTP_PORT,
            new ECFHttpClientProtocolSocketFactory(SocketFactory.getDefault(), source, socketListener));

    Trace.trace(Activator.PLUGIN_ID, "registering http scheme"); //$NON-NLS-1$
    schemeRegistry.register(http);/* w w  w  . j  a  v a 2  s  .  c o m*/

    ISSLSocketFactoryModifier sslSocketFactoryModifier = Activator.getDefault().getSSLSocketFactoryModifier();

    if (sslSocketFactoryModifier == null) {
        sslSocketFactoryModifier = new HttpClientDefaultSSLSocketFactoryModifier();
    }

    SSLSocketFactory sslSocketFactory = null;
    try {
        sslSocketFactory = sslSocketFactoryModifier.getSSLSocketFactory();
    } catch (IOException e) {
        Trace.catching(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_CATCHING, ISSLSocketFactoryModifier.class,
                "getSSLSocketFactory()", e); //$NON-NLS-1$
        Trace.throwing(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_THROWING,
                HttpClientRetrieveFileTransfer.class, "registerSchemes()", e); //$NON-NLS-1$
        throw new ECFRuntimeException("Unable to instantiate schemes for HttpClient.", e); //$NON-NLS-1$
    }

    Scheme https = new Scheme(HttpClientRetrieveFileTransfer.HTTPS, HTTPS_PORT,
            new ECFHttpClientSecureProtocolSocketFactory(sslSocketFactory, source, socketListener));
    Trace.trace(Activator.PLUGIN_ID, "registering https scheme; modifier=" + sslSocketFactoryModifier); //$NON-NLS-1$
    schemeRegistry.register(https);

    // SPNEGO is not supported, so remove it from the list
    List authpref = new ArrayList(3);
    authpref.add(AuthPolicy.NTLM);
    authpref.add(AuthPolicy.DIGEST);
    authpref.add(AuthPolicy.BASIC);

    httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);
}

From source file:org.springframework.data.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,
                    Collections.singletonList(authPolicy));
        }//from w w w.j  a v  a2s  .co m
    }
}