Example usage for org.apache.http.auth AuthScope ANY

List of usage examples for org.apache.http.auth AuthScope ANY

Introduction

In this page you can find the example usage for org.apache.http.auth AuthScope ANY.

Prototype

AuthScope ANY

To view the source code for org.apache.http.auth AuthScope ANY.

Click Source Link

Document

Default scope matching any host, port, realm and authentication scheme.

Usage

From source file:de.shadowhunt.subversion.internal.AbstractHelper.java

public HttpClient getHttpClient(final String username, final HttpRequestInterceptor... interceptors) {
    final HttpClientBuilder builder = HttpClientBuilder.create();

    final CredentialsProvider cp = new BasicCredentialsProvider();
    final Credentials credentials = new UsernamePasswordCredentials(username, PASSWORD);
    cp.setCredentials(AuthScope.ANY, credentials);
    builder.setDefaultCredentialsProvider(cp);

    for (HttpRequestInterceptor interceptor : interceptors) {
        builder.addInterceptorFirst(interceptor);
    }// ww  w .  ja va  2s.com

    builder.setRetryHandler(new SubversionRequestRetryHandler());
    return builder.build();
}

From source file:org.apache.solr.client.solrj.impl.Krb5HttpClientConfigurer.java

public void configure(DefaultHttpClient httpClient, SolrParams config) {
    super.configure(httpClient, config);

    if (System.getProperty(LOGIN_CONFIG_PROP) != null) {
        String configValue = System.getProperty(LOGIN_CONFIG_PROP);

        if (configValue != null) {
            logger.info("Setting up SPNego auth with config: " + configValue);
            final String useSubjectCredsProp = "javax.security.auth.useSubjectCredsOnly";
            String useSubjectCredsVal = System.getProperty(useSubjectCredsProp);

            // "javax.security.auth.useSubjectCredsOnly" should be false so that the underlying
            // authentication mechanism can load the credentials from the JAAS configuration.
            if (useSubjectCredsVal == null) {
                System.setProperty(useSubjectCredsProp, "false");
            } else if (!useSubjectCredsVal.toLowerCase(Locale.ROOT).equals("false")) {
                // Don't overwrite the prop value if it's already been written to something else,
                // but log because it is likely the Credentials won't be loaded correctly.
                logger.warn("System Property: " + useSubjectCredsProp + " set to: " + useSubjectCredsVal
                        + " not false.  SPNego authentication may not be successful.");
            }/*www.  ja v  a2  s.  com*/

            javax.security.auth.login.Configuration.setConfiguration(jaasConfig);
            //Enable only SPNEGO authentication scheme.
            AuthSchemeRegistry registry = new AuthSchemeRegistry();
            registry.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, false));
            httpClient.setAuthSchemes(registry);
            // Get the credentials from the JAAS configuration rather than here
            Credentials useJaasCreds = new Credentials() {
                public String getPassword() {
                    return null;
                }

                public Principal getUserPrincipal() {
                    return null;
                }
            };

            SolrPortAwareCookieSpecFactory cookieFactory = new SolrPortAwareCookieSpecFactory();
            httpClient.getCookieSpecs().register(cookieFactory.POLICY_NAME, cookieFactory);
            httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, cookieFactory.POLICY_NAME);

            httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, useJaasCreds);

            httpClient.addRequestInterceptor(bufferedEntityInterceptor);
        } else {
            httpClient.getCredentialsProvider().clear();
        }
    }
}

From source file:org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientSpnegoImpl.java

/**
 * Constructs an HTTP client with user specified by the given credentials.
 *
 * @param url The URL for the Avatica server
 * @param credential The GSS credentials
 *//*from w  w  w. ja v  a 2s .  c o  m*/
public AvaticaCommonsHttpClientSpnegoImpl(URL url, GSSCredential credential) {
    this.url = Objects.requireNonNull(url);

    pool = new PoolingHttpClientConnectionManager();
    // Increase max total connection to 100
    final String maxCnxns = System.getProperty(CACHED_CONNECTIONS_MAX_KEY, CACHED_CONNECTIONS_MAX_DEFAULT);
    pool.setMaxTotal(Integer.parseInt(maxCnxns));
    // Increase default max connection per route to 25
    final String maxCnxnsPerRoute = System.getProperty(CACHED_CONNECTIONS_MAX_PER_ROUTE_KEY,
            CACHED_CONNECTIONS_MAX_PER_ROUTE_DEFAULT);
    pool.setDefaultMaxPerRoute(Integer.parseInt(maxCnxnsPerRoute));

    this.host = new HttpHost(url.getHost(), url.getPort());

    this.authRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO,
            new SPNegoSchemeFactory(STRIP_PORT_ON_SERVER_LOOKUP, USE_CANONICAL_HOSTNAME)).build();

    this.credentialsProvider = new BasicCredentialsProvider();
    if (null != credential) {
        // Non-null credential should be used directly with KerberosCredentials.
        this.credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));
    } else {
        // A null credential implies that the user is logged in via JAAS using the
        // java.security.auth.login.config system property
        this.credentialsProvider.setCredentials(AuthScope.ANY, EmptyCredentials.INSTANCE);
    }

    this.authCache = new BasicAuthCache();

    // A single thread-safe HttpClient, pooling connections via the ConnectionManager
    this.client = HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry).setConnectionManager(pool)
            .build();
}

From source file:be.cytomine.client.HttpClient.java

public void connect(String url, String username, String password) throws IOException {
    isAuthByPrivateKey = false;// ww  w .j  av a  2s  . c  o m
    log.info("Connection to " + url + " with login=" + username + " and pass=" + password);
    URL = new URL(url);
    targetHost = new HttpHost(URL.getHost(), URL.getPort());
    client = new DefaultHttpClient();
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local
    // auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    // Add AuthCache to the execution context
    localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    // Set credentials
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
    client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
}

From source file:org.aludratest.service.gui.web.selenium.TAFMSSeleniumResourceService.java

@Override
public String acquire() {
    // prepare a JSON query to the given TAFMS server
    JSONObject query = new JSONObject();

    try {//from ww w. j a  v a2 s  . com
        query.put("resourceType", "selenium");
        query.put("niceLevel", configuration.getIntValue("tafms.niceLevel", 0));
        String jobName = configuration.getStringValue("tafms.jobName");
        if (jobName != null && !"".equals(jobName)) {
            query.put("jobName", jobName);
        }
    } catch (JSONException e) {
    }

    // prepare authentication
    BasicCredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
            configuration.getStringValue("tafms.user"), configuration.getStringValue("tafms.password")));

    CloseableHttpClient client = HttpClientBuilder.create()
            .setConnectionReuseStrategy(new NoConnectionReuseStrategy()).disableConnectionState()
            .disableAutomaticRetries().setDefaultCredentialsProvider(provider).build();

    String message = null;
    try {
        boolean wait;

        // use preemptive authentication to avoid double connection count
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        URL url = new URL(getTafmsUrl());
        HttpHost host = new HttpHost(url.getHost(), url.getPort() == -1 ? url.getDefaultPort() : url.getPort(),
                url.getProtocol());
        authCache.put(host, basicAuth);

        // Add AuthCache to the execution context
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);

        do {
            // send a POST request to resource URL
            HttpPost request = new HttpPost(getTafmsUrl() + "resource");

            // attach query as JSON string data
            request.setEntity(new StringEntity(query.toString(), ContentType.APPLICATION_JSON));

            CloseableHttpResponse response = null;

            // fire request
            response = client.execute(request, localcontext);

            try {
                if (response.getStatusLine() == null) {
                    throw new ClientProtocolException("No HTTP status line transmitted");
                }

                message = extractMessage(response);
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    LOG.error("Exception when querying TAFMS server for resource. HTTP Status: "
                            + response.getStatusLine().getStatusCode() + ", message: " + message);
                    return null;
                }

                JSONObject object = new JSONObject(message);
                if (object.has("errorMessage")) {
                    LOG.error("TAFMS server reported an error: " + object.get("errorMessage"));
                    return null;
                }

                // continue wait?
                if (object.has("waiting") && object.getBoolean("waiting")) {
                    wait = true;
                    query.put("requestId", object.getString("requestId"));
                } else {
                    JSONObject resource = object.optJSONObject("resource");
                    if (resource == null) {
                        LOG.error("TAFMS server response did not provide a resource. Message was: " + message);
                        return null;
                    }

                    String sUrl = resource.getString("url");
                    hostResourceIds.put(sUrl, object.getString("requestId"));

                    return sUrl;
                }
            } finally {
                IOUtils.closeQuietly(response);
            }
        } while (wait);

        // should never come here
        return null;
    } catch (ClientProtocolException e) {
        LOG.error("Exception in HTTP transmission", e);
        return null;
    } catch (IOException e) {
        LOG.error("Exception in communication with TAFMS server", e);
        return null;
    } catch (JSONException e) {
        LOG.error("Invalid JSON received from TAFMS server. JSON message was: " + message, e);
        return null;
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:HybridIT.com.fourspaces.couchdb.Session.java

/**
* Constructor for obtaining a Session with an HTTP-AUTH username/password and (optionally) a secure connection
* This isn't supported by CouchDB - you need a proxy in front to use this
* @param host - hostname//from w w  w.  j a v  a 2 s .  c o  m
* @param port - port to use
* @param user - username
* @param pass - password
* @param secure  - use an SSL connection?
*/
public Session(String host, int port, String user, String pass, boolean usesAuth, boolean secure) {
    this.host = host;
    this.port = port;
    this.user = user;
    this.pass = pass;
    this.usesAuth = usesAuth;
    this.secure = secure;

    httpParams = new BasicHttpParams();
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
    DefaultHttpClient defaultClient = new DefaultHttpClient(connManager, httpParams);
    if (user != null) {
        defaultClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(user, pass));
    }

    this.httpClient = defaultClient;

    setUserAgent("couchdb4j");
    setSocketTimeout((30 * 1000));
    setConnectionTimeout((15 * 1000));

}

From source file:edu.cornell.mannlib.vitro.webapp.rdfservice.impl.virtuoso.RDFServiceVirtuoso.java

/**
 * We need an HttpContext that will provide username and password in
 * response to a basic authentication challenge.
 *//*w  w w  . ja va2s . c om*/
private HttpContext createHttpContext() {
    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    BasicHttpContext context = new BasicHttpContext();
    context.setAttribute(ClientContext.CREDS_PROVIDER, provider);
    return context;
}

From source file:io.wcm.caravan.commons.httpclient.impl.HttpClientItemAsyncTest.java

@Test
public void testHttpAuthentication() {
    HttpClientConfigImpl config = context.registerInjectActivateService(new HttpClientConfigImpl(),
            ImmutableMap.<String, Object>builder().put(HTTP_USER_PROPERTY, HTTP_USER_PROPERTY)
                    .put(HTTP_PASSWORD_PROPERTY, "httpPasswd").build());

    HttpClientItem item = new HttpClientItem(config);
    HttpAsyncClient client = item.getHttpAsyncClient();

    Credentials credentials = HttpClientTestUtils.getCredentialsProvider(client).getCredentials(AuthScope.ANY);
    assertNotNull(credentials);//from  w ww. j a v  a  2s  . c  om
    assertEquals(HTTP_USER_PROPERTY, credentials.getUserPrincipal().getName());
    assertEquals("httpPasswd", credentials.getPassword());
    item.close();
}