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:org.openremote.controller.protocol.http.HttpGetCommand.java

private String requestURL() {
    DefaultHttpClient client = new DefaultHttpClient();

    if (getUsername() != null) {
        CredentialsProvider cred = new BasicCredentialsProvider();

        cred.setCredentials(new AuthScope(AuthScope.ANY),
                new UsernamePasswordCredentials(getUsername(), new String(password)));

        client.setCredentialsProvider(cred);
    }/*w  ww  . j  a  va2 s.  c o  m*/

    HttpGet httpget = new HttpGet(url.toExternalForm());

    String resp = "";

    try {
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        resp = client.execute(httpget, responseHandler);
        logger.info("received message: " + resp);
    }

    catch (Exception e) {
        logger.error("HttpGetCommand could not execute", e);
    }

    return resp;
}

From source file:edu.washington.shibboleth.attribute.resolver.dc.rws.HttpDataSource.java

/**
 * Initializes the connector and prepares it for use.
 *///from   ww w  . j  av  a2  s. com
public void initialize() throws IOException {
    log.info("HttpDataSource: initialize");

    SSLConnectionSocketFactory sf = getSocketFactory();
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sf).build();

    connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    connectionManager.setMaxTotal(maxConnections);
    connectionManager.setDefaultMaxPerRoute(maxConnections);

    /*
     * Create our client 
     */

    // HttpClientBuilder cb = HttpClients.custom().setConnectionManager(connectionManager);
    HttpClientBuilder cb = HttpClientBuilder.create().setConnectionManager(connectionManager);
    // requires lib 4.x
    // cb = cb.setConnectionManagerShared(true);

    if (username != null && password != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username,
                password);
        credsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
        cb = cb.setDefaultCredentialsProvider(credsProvider);
        log.info("HttpDataSource: added basic creds ");
    }
    httpClient = cb.build();
}

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

public SolrHttpClientBuilder getBuilder(SolrHttpClientBuilder builder) {
    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.");
            }// ww  w.ja  va 2  s.co m

            javax.security.auth.login.Configuration.setConfiguration(jaasConfig);
            //Enable only SPNEGO authentication scheme.

            builder.setAuthSchemeRegistryProvider(() -> {
                Lookup<AuthSchemeProvider> authProviders = RegistryBuilder.<AuthSchemeProvider>create()
                        .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, false)).build();
                return authProviders;
            });
            // Get the credentials from the JAAS configuration rather than here
            Credentials useJaasCreds = new Credentials() {
                public String getPassword() {
                    return null;
                }

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

            HttpClientUtil.setCookiePolicy(SolrPortAwareCookieSpecFactory.POLICY_NAME);

            builder.setCookieSpecRegistryProvider(() -> {
                SolrPortAwareCookieSpecFactory cookieFactory = new SolrPortAwareCookieSpecFactory();

                Lookup<CookieSpecProvider> cookieRegistry = RegistryBuilder.<CookieSpecProvider>create()
                        .register(SolrPortAwareCookieSpecFactory.POLICY_NAME, cookieFactory).build();

                return cookieRegistry;
            });

            builder.setDefaultCredentialsProvider(() -> {
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(AuthScope.ANY, useJaasCreds);
                return credentialsProvider;
            });
            HttpClientUtil.addRequestInterceptor(bufferedEntityInterceptor);
        }
    }

    return builder;
}

From source file:com.vmware.photon.controller.nsxclient.RestClient.java

/**
 * Creates a HTTP client context with preemptive basic authentication.
 *///from   ww  w  . j  a  v a2  s.  co m
private HttpClientContext getHttpClientContext(String target, String username, String password) {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    HttpHost targetHost = HttpHost.create(target);
    AuthCache authCache = new BasicAuthCache();
    authCache.put(targetHost, new BasicScheme());

    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthCache(authCache);

    return context;
}

From source file:org.prx.prp.utility.HttpHelper.java

private String performRequest(final String contentType, final String url, final String user, final String pass,
        final Map<String, String> headers, final Map<String, String> params, final int requestType) {
    if ((user != null) && (pass != null)) {
        HttpHelper.client.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(user, pass));
    }//from   ww  w .ja  va  2s .c  o m

    final Map<String, String> sendHeaders = new HashMap<String, String>();

    if ((headers != null) && (headers.size() > 0)) {
        sendHeaders.putAll(headers);
    }

    if (requestType == HttpHelper.POST_TYPE) {
        sendHeaders.put(HttpHelper.CONTENT_TYPE, contentType);
    }

    if (sendHeaders.size() > 0) {
        HttpHelper.client.addRequestInterceptor(new HttpRequestInterceptor() {
            public void process(final HttpRequest request, final HttpContext context)
                    throws HttpException, IOException {
                for (String key : sendHeaders.keySet()) {
                    if (!request.containsHeader(key)) {
                        request.addHeader(key, sendHeaders.get(key));
                    }
                }
            }
        });
    }

    HttpRequestBase method = null;
    if (requestType == HttpHelper.POST_TYPE) {
        method = new HttpPost(url);
        List<NameValuePair> nvps = null;

        if ((params != null) && (params.size() > 0)) {
            nvps = new ArrayList<NameValuePair>();

            for (Map.Entry<String, String> entry : params.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }

        if (nvps != null) {
            try {
                HttpPost methodPost = (HttpPost) method;
                methodPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            } catch (UnsupportedEncodingException e) {
                Log.d("PRPAND", e.getMessage());
            }
        }
    } else if (requestType == HttpHelper.GET_TYPE) {

        String authUrl = url + (url.indexOf('?') != -1 ? '&' : '?') + "key=" + DatabaseHelper.getApiKey();

        Log.d("PRPAND", authUrl);
        method = new HttpGet(authUrl);
    }

    return this.execute(method);
}

From source file:app.android.auto.net.sampleapp.oauth.blackwork.EasyHttpClient.java

/**
 * Constructor which handles credentials for the connection (only if username and password are set)
 *
 * @param username/*from  w  w  w .j a  v  a2 s  .com*/
 * @param password
 */
public EasyHttpClient(String username, String password) {
    if (username != null && password != null) {
        UsernamePasswordCredentials c = new UsernamePasswordCredentials(username, password);
        BasicCredentialsProvider cP = new BasicCredentialsProvider();
        cP.setCredentials(AuthScope.ANY, c);
        setCredentialsProvider(cP);
    }
}

From source file:aajavafx.MedicinesController.java

public ObservableList<Medicines> getMedicines() throws IOException, JSONException {

    ObservableList<Medicines> medicines = FXCollections.observableArrayList();
    //Managers manager = new Managers();
    Gson gson = new Gson();
    JSONObject jo = new JSONObject();

    // SSL update .......
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
    provider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    HttpGet get = new HttpGet("http://localhost:8080/MainServerREST/api/medicines");
    HttpResponse response = client.execute(get);
    System.out.println("RESPONSE IS: " + response);
    JSONArray jsonArray = new JSONArray(
            IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8")));
    // ...........
    //JSONArray jsonArray = new JSONArray(IOUtils.toString(new URL(MedicineRootURL), Charset.forName("UTF-8")));
    System.out.println(jsonArray);
    for (int i = 0; i < jsonArray.length(); i++) {
        jo = (JSONObject) jsonArray.getJSONObject(i);
        Medicines medicine = gson.fromJson(jo.toString(), Medicines.class);
        System.out.println("JSON OBJECT #" + i + " " + jo);
        medicines.add(medicine);/*from w ww.ja  va2 s  . co m*/

    }
    return medicines;
}

From source file:org.sonatype.nexus.examples.url.UrlRealmTest.java

@Test(expected = UnknownAccountException.class)
public void testAuthcJunkCreds() throws Exception {
    // build client
    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("fakeuser", "hack-me-in"));
    httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    when(hc4Provider.createHttpClient(Mockito.any(RemoteStorageContext.class))).thenReturn(httpClient);

    urlRealm.getAuthenticationInfo(new UsernamePasswordToken("fakeuser", "hack-me-in"));
}

From source file:cf.spring.servicebroker.CatalogTest.java

@Test
public void spelCatalogCredentials() throws Exception {
    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(CONFIGURABLE_USERNAME, CONFIGURABLE_PASSWORD));
    final SpringApplication application = new SpringApplication(SpelServiceBrokerCatalog.class);
    try (ConfigurableApplicationContext context = application.run();
            CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider)
                    .build();) {//  w ww.  j  a  v a  2  s .c  om
        final HttpUriRequest catalogRequest = RequestBuilder.get()
                .setUri("http://localhost:8080" + Constants.CATALOG_URI).build();
        final CloseableHttpResponse response = client.execute(catalogRequest);
        assertEquals(response.getStatusLine().getStatusCode(), 200);
    }
}