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.glassfish.jersey.apache.connector.AuthTest.java

@Test
public void testPreemptiveAuthPost() {
    CredentialsProvider credentialsProvider = new org.apache.http.impl.client.BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("name", "password"));

    ClientConfig cc = new ClientConfig();
    cc.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider)
            .property(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, true);
    cc.connectorProvider(new ApacheConnectorProvider());
    Client client = ClientBuilder.newClient(cc);

    WebTarget r = client.target(getBaseUri());
    assertEquals("POST", r.request().post(Entity.text("POST"), String.class));
}

From source file:no.kantega.publishing.jobs.xmlimport.XMLImportJob.java

@PostConstruct
private void init() {
    int timeout = configuration.getInt("httpclient.connectiontimeout", 10000);
    String proxyHost = configuration.getString("httpclient.proxy.host");
    String proxyPort = configuration.getString("httpclient.proxy.port");

    String proxyUser = configuration.getString("httpclient.proxy.username");

    String proxyPassword = configuration.getString("httpclient.proxy.password");
    if (isNotBlank(proxyHost)) {
        HttpHost proxy = new HttpHost(proxyHost, Integer.parseInt(proxyPort));

        httpClientBuilder = HttpClients.custom()
                .setDefaultRequestConfig(
                        RequestConfig.custom().setRedirectsEnabled(true).setConnectTimeout(timeout)
                                .setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build())
                .setProxy(proxy);//from  w w  w .  j av  a 2  s . c  o  m

        if (isNotBlank(proxyUser)) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
            httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
        }
    } else {
        httpClientBuilder = HttpClients.custom().setDefaultRequestConfig(
                RequestConfig.custom().setRedirectsEnabled(true).setConnectTimeout(timeout)
                        .setSocketTimeout(timeout).setConnectionRequestTimeout(timeout).build());
    }
}

From source file:com.controlj.experiment.bulktrend.trendclient.TrendClient.java

public void go() {
    DefaultHttpClient client = null;/*from  w  w  w . j  a va  2 s. c  o  m*/
    try {
        prepareForResponse();

        if (altInput == null) {
            client = new DefaultHttpClient();

            // Set up preemptive Basic Authentication
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);
            client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

            BasicHttpContext localcontext = new BasicHttpContext();
            BasicScheme basicAuth = new BasicScheme();
            localcontext.setAttribute("preemptive-auth", basicAuth);
            client.addRequestInterceptor(new PreemptiveAuthRequestInterceptor(), 0);

            if (zip) {
                client.addRequestInterceptor(new GZipRequestInterceptor());
                client.addResponseInterceptor(new GZipResponseInterceptor());
            }

            HttpPost post = new HttpPost(url);

            try {
                setPostData(post);
                HttpResponse response = client.execute(post, localcontext);
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    System.err.println(
                            "Error: Web Service response code of: " + response.getStatusLine().getStatusCode());
                    return;
                }
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    parser.parseResponse(ids.size(), entity.getContent());
                }

            } catch (IOException e) {
                System.err.println("IO Error reading response");
                e.printStackTrace();
            }
        } else { // Alternate input (typically from a file) for testing
            try {
                parser.parseResponse(ids.size(), altInput);
            } catch (IOException e) {
                System.err.println("IO Error reading response");
                e.printStackTrace();
            }
        }
    } finally {
        if (client != null) {
            client.getConnectionManager().shutdown();
        }
    }
    /*
    try {
    parser.parseResponse(ids.size(), new FileInputStream(new File("response.dump")));
    } catch (IOException e) {
    e.printStackTrace(); 
    }
    */

}

From source file:org.wildfly.test.integration.elytron.http.PasswordMechTestBase.java

@Test
public void testInvalidCredential() throws Exception {
    HttpGet request = new HttpGet(new URI(url.toExternalForm() + "role1"));
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1", "password1wrong");

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, credentials);

    try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            .build()) {//from   w w  w.  ja  va 2s .  c o  m
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            int statusCode = response.getStatusLine().getStatusCode();
            assertEquals("Unexpected status code in HTTP response.", SC_UNAUTHORIZED, statusCode);
        }
    }
}

From source file:census.couchdroid.CouchSession.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  a2  s. co m
 * @param port - port to use
 * @param user - username
 * @param pass - password
 * @param secure  - use an SSL connection?
 */
public CouchSession(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:io.wcm.caravan.commons.httpasyncclient.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());

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

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

From source file:com.microsoft.alm.plugin.context.ServerContextTest.java

@Test
public void getClientConfig() {
    AuthenticationInfo info = new AuthenticationInfo("user1", "pass", "server1", "4display");
    final ClientConfig config = ServerContext.getClientConfig(ServerContext.Type.TFS, info, false);

    final Map<String, Object> properties = config.getProperties();
    Assert.assertEquals(3, properties.size());

    Assert.assertEquals(false, properties.get(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION));
    Assert.assertEquals(RequestEntityProcessing.BUFFERED,
            properties.get(ClientProperties.REQUEST_ENTITY_PROCESSING));

    final CredentialsProvider cp = (CredentialsProvider) properties
            .get(ApacheClientProperties.CREDENTIALS_PROVIDER);
    final Credentials credentials = cp.getCredentials(AuthScope.ANY);
    Assert.assertEquals(info.getPassword(), credentials.getPassword());
    Assert.assertEquals(info.getUserName(), credentials.getUserPrincipal().getName());

    // Make sure Fiddler properties get set if property is on
    final ClientConfig config2 = ServerContext.getClientConfig(ServerContext.Type.TFS, info, true);
    final Map<String, Object> properties2 = config2.getProperties();
    //proxy setting doesn't automatically mean we need to setup ssl trust store anymore
    Assert.assertEquals(4, properties2.size());
    Assert.assertNotNull(properties2.get(ClientProperties.PROXY_URI));
    Assert.assertNull(properties2.get(ApacheClientProperties.SSL_CONFIG));

    info = new AuthenticationInfo("users1", "pass", "https://tfsonprem.test", "4display");
    final ClientConfig config3 = ServerContext.getClientConfig(ServerContext.Type.TFS, info, false);
    final Map<String, Object> properties3 = config3.getProperties();
    Assert.assertEquals(4, properties3.size());
    Assert.assertNull(properties3.get(ClientProperties.PROXY_URI));
    Assert.assertNotNull(properties3.get(ApacheClientProperties.SSL_CONFIG));
}

From source file:org.artificer.test.AbstractIntegrationTest.java

protected ClientRequest clientRequest(String endpoint) {
    DefaultHttpClient client = new DefaultHttpClient();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(USERNAME, PASSWORD);
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    HttpHost targetHost = new HttpHost(HOST, PORT);
    authCache.put(targetHost, basicAuth);
    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(client, localContext);

    ClientRequest clientRequest = new ClientRequest(BASE_URL + endpoint, executor);
    return clientRequest;
}

From source file:org.nebula.framework.client.NebulaRestClient.java

private HttpClientContext createPreemptiveBasicAuthentication(String accessId, String password) {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(accessId, password));

    AuthCache authCache = new BasicAuthCache();
    authCache.put(target, new BasicScheme());

    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);//from   w  w w  . java2s  .  com

    return context;
}