Java Code Examples for org.apache.http.client.CredentialsProvider#setCredentials()

The following examples show how to use org.apache.http.client.CredentialsProvider#setCredentials() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ElasticsearchRestClientInstrumentationIT.java    From apm-agent-java with Apache License 2.0 8 votes vote down vote up
@BeforeClass
public static void startElasticsearchContainerAndClient() throws IOException {
    container = new ElasticsearchContainer(ELASTICSEARCH_CONTAINER_VERSION);
    container.start();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USER_NAME, PASSWORD));

    RestClientBuilder builder = RestClient.builder(HttpHost.create(container.getHttpHostAddress()))
        .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));

    client = new RestHighLevelClient(builder);

    client.indices().create(new CreateIndexRequest(INDEX), RequestOptions.DEFAULT);
    reporter.reset();
}
 
Example 2
Source File: HttpClientConfigurer.java    From spring-cloud-dataflow with Apache License 2.0 7 votes vote down vote up
/**
 * Configures the {@link HttpClientBuilder} with a proxy host. If the
 * {@code proxyUsername} and {@code proxyPassword} are not {@code null}
 * then a {@link CredentialsProvider} is also configured for the proxy host.
 *
 * @param proxyUri Must not be null and must be configured with a scheme (http or https).
 * @param proxyUsername May be null
 * @param proxyPassword May be null
 * @return a reference to {@code this} to enable chained method invocation
 */
public HttpClientConfigurer withProxyCredentials(URI proxyUri, String proxyUsername, String proxyPassword) {

	Assert.notNull(proxyUri, "The proxyUri must not be null.");
	Assert.hasText(proxyUri.getScheme(), "The scheme component of the proxyUri must not be empty.");

	httpClientBuilder
		.setProxy(new HttpHost(proxyUri.getHost(), proxyUri.getPort(), proxyUri.getScheme()));
	if (proxyUsername !=null && proxyPassword != null) {
		final CredentialsProvider credentialsProvider = this.getOrInitializeCredentialsProvider();
		credentialsProvider.setCredentials(
			new AuthScope(proxyUri.getHost(), proxyUri.getPort()),
			new UsernamePasswordCredentials(proxyUsername, proxyPassword));
		httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
			.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
	}
	return this;
}
 
Example 3
Source File: AbstractUnitTest.java    From elasticsearch-shield-kerberos-realm with Apache License 2.0 6 votes vote down vote up
protected final CloseableHttpClient getHttpClient(final boolean useSpnego) throws Exception {

        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        final HttpClientBuilder hcb = HttpClients.custom();

        if (useSpnego) {
            //SPNEGO/Kerberos setup
            log.debug("SPNEGO activated");
            final AuthSchemeProvider nsf = new SPNegoSchemeFactory(true);//  new NegotiateSchemeProvider();
            final Credentials jaasCreds = new JaasCredentials();
            credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.SPNEGO), jaasCreds);
            credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM), new NTCredentials("Guest", "Guest", "Guest",
                    "Guest"));
            final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create()
                    .register(AuthSchemes.SPNEGO, nsf).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build();

            hcb.setDefaultAuthSchemeRegistry(authSchemeRegistry);
        }

        hcb.setDefaultCredentialsProvider(credsProvider);
        hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(10 * 1000).build());
        final CloseableHttpClient httpClient = hcb.build();
        return httpClient;
    }
 
Example 4
Source File: HttpDispatcher.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static HttpDispatcher getInstance(String uri, Credentials credentials) {

        HttpDispatcher dispatcher = new HttpDispatcher(new HttpHost(uri),
                new BasicHttpContext());

        CredentialsProvider credsProvider = new BasicCredentialsProvider();

        AuthScope authScope = new AuthScope(
                dispatcher.host.getHostName(),
                dispatcher.host.getPort());

        credsProvider.setCredentials(authScope, credentials);

        ((DefaultHttpClient) dispatcher.client).getCredentialsProvider().setCredentials(
                authScope, credentials);
        return dispatcher;
    }
 
Example 5
Source File: WxPayServiceApacheHttpImpl.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
private HttpClientBuilder createHttpClientBuilder(boolean useKey) throws WxPayException {
  HttpClientBuilder httpClientBuilder = HttpClients.custom();
  if (useKey) {
    this.initSSLContext(httpClientBuilder);
  }

  if (StringUtils.isNotBlank(this.getConfig().getHttpProxyHost())
    && this.getConfig().getHttpProxyPort() > 0) {
    // 使用代理服务器 需要用户认证的代理服务器
    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(
      new AuthScope(this.getConfig().getHttpProxyHost(), this.getConfig().getHttpProxyPort()),
      new UsernamePasswordCredentials(this.getConfig().getHttpProxyUsername(), this.getConfig().getHttpProxyPassword()));
    httpClientBuilder.setDefaultCredentialsProvider(provider);
  }
  return httpClientBuilder;
}
 
Example 6
Source File: ElasticsearchConnection.java    From components with Apache License 2.0 6 votes vote down vote up
public static RestClient createClient(ElasticsearchDatastoreProperties datastore) throws MalformedURLException {
    String urlStr = datastore.nodes.getValue();
    String[] urls = urlStr.split(",");
    HttpHost[] hosts = new HttpHost[urls.length];
    int i = 0;
    for (String address : urls) {
        URL url = new URL("http://" + address);
        hosts[i] = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        i++;
    }
    RestClientBuilder restClientBuilder = RestClient.builder(hosts);
    if (datastore.auth.useAuth.getValue()) {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(datastore.auth.userId.getValue(), datastore.auth.password.getValue()));
        restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {

            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
                return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }
        });
    }
    return restClientBuilder.build();
}
 
Example 7
Source File: SlaveConnectionManager.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
public HttpClient createHttpClient( String user, String password,
                                             String proxyHost, int proxyPort, AuthScope authScope ) {
  HttpHost httpHost = new HttpHost( proxyHost, proxyPort );

  RequestConfig requestConfig = RequestConfig.custom()
    .setProxy( httpHost )
    .build();

  CredentialsProvider provider = new BasicCredentialsProvider();
  UsernamePasswordCredentials credentials = new UsernamePasswordCredentials( user, password );
  provider.setCredentials( authScope, credentials );

  return
    HttpClientBuilder
      .create()
      .setDefaultCredentialsProvider( provider )
      .setDefaultRequestConfig( requestConfig )
      .setConnectionManager( manager )
      .build();
}
 
Example 8
Source File: TriplestoreStorage.java    From IGUANA with GNU Affero General Public License v3.0 5 votes vote down vote up
private HttpClient createHttpClient(){
	CredentialsProvider credsProvider = new BasicCredentialsProvider();
	if(user !=null && pwd !=null){
		Credentials credentials = new UsernamePasswordCredentials(user, pwd);
		credsProvider.setCredentials(AuthScope.ANY, credentials);
	}
	HttpClient httpclient = HttpClients.custom()
	    .setDefaultCredentialsProvider(credsProvider)
	    .build();
	return httpclient;
}
 
Example 9
Source File: ElasticSearchHighSink.java    From ns4_gear_watchdog with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void start() {
    logger.info("start elasticsearch sink......");
    HttpHost[] httpHosts = new HttpHost[serverAddresses.length];
    for (int i = 0; i < serverAddresses.length; i++) {
        String[] hostPort = serverAddresses[i].trim().split(":");
        String host = hostPort[0].trim();
        int port = hostPort.length == 2 ? Integer.parseInt(hostPort[1].trim())
                : DEFAULT_PORT;
        logger.info("elasticsearch host:{},port:{}", host, port);
        httpHosts[i] = new HttpHost(host, port, "http");
    }

    RestClientBuilder builder = RestClient.builder(httpHosts);
    if (StringUtils.isNotBlank(serverUser) || StringUtils.isNotBlank(serverPassword)) {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(serverUser, serverPassword));
        builder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
            @Override
            public HttpAsyncClientBuilder customizeHttpClient(
                    HttpAsyncClientBuilder httpClientBuilder) {
                return httpClientBuilder
                        .setDefaultCredentialsProvider(credentialsProvider);
            }
        });
    }
    client = new RestHighLevelClient(builder);
    sinkCounter.start();
    super.start();
}
 
Example 10
Source File: GatewayBasicFuncTest.java    From knox with Apache License 2.0 5 votes vote down vote up
private String oozieQueryJobStatus( String user, String password, String id, int status ) throws Exception {
  driver.getMock( "OOZIE" )
      .expect()
      .method( "GET" )
      .pathInfo( "/v1/job/" + id )
      .respond()
      .status( HttpStatus.SC_OK )
      .content( driver.getResourceBytes( "oozie-job-show-info.json" ) )
      .contentType( "application/json" );

  //NOTE:  For some reason REST-assured doesn't like this and ends up failing with Content-Length issues.
  URL url = new URL( driver.getUrl( "OOZIE" ) + "/v1/job/" + id + ( driver.isUseGateway() ? "" : "?user.name=" + user ) );
  HttpHost targetHost = new HttpHost( url.getHost(), url.getPort(), url.getProtocol() );
  HttpClientBuilder builder = HttpClientBuilder.create();
  CloseableHttpClient client = builder.build();

  HttpClientContext context = HttpClientContext.create();
  CredentialsProvider credsProvider = new BasicCredentialsProvider();
  credsProvider.setCredentials(
      new AuthScope( targetHost ),
      new UsernamePasswordCredentials( user, password ) );
  context.setCredentialsProvider( credsProvider );

  // 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
  context.setAuthCache( authCache );

  HttpGet request = new HttpGet( url.toURI() );
  request.setHeader("X-XSRF-Header", "ksdhfjkhdsjkf");
  HttpResponse response = client.execute( targetHost, request, context );
  assertThat( response.getStatusLine().getStatusCode(), Matchers.is(status) );
  String json = EntityUtils.toString( response.getEntity() );
  return JsonPath.from(json).getString( "status" );
}
 
Example 11
Source File: HttpManagementConstantHeadersTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Before
public void createClient() throws Exception {
    String address = managementClient.getMgmtAddress();
    this.managementUrl = new URL("http", address, MGMT_PORT, MGMT_CTX);
    this.errorUrl = new URL("http", address, MGMT_PORT, ERROR_CTX);

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(managementUrl.getHost(), managementUrl.getPort()), new UsernamePasswordCredentials(Authentication.USERNAME, Authentication.PASSWORD));

    this.httpClient = HttpClients.custom()
            .setDefaultCredentialsProvider(credsProvider)
            .build();
}
 
Example 12
Source File: HelloWorldWebScriptIT.java    From alfresco-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testWebScriptCall() throws Exception {
    String webscriptURL = getPlatformEndpoint() + "/service/sample/helloworld";
    String expectedResponse = "Message: 'Hello from JS!' 'HelloFromJava'";

    // Login credentials for Alfresco Repo
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "admin");
    provider.setCredentials(AuthScope.ANY, credentials);

    // Create HTTP Client with credentials
    CloseableHttpClient httpclient = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(provider)
            .build();

    // Execute Web Script call
    try {
        HttpGet httpget = new HttpGet(webscriptURL);
        HttpResponse httpResponse = httpclient.execute(httpget);
        assertEquals("Incorrect HTTP Response Status",
                HttpStatus.SC_OK, httpResponse.getStatusLine().getStatusCode());
        HttpEntity entity = httpResponse.getEntity();
        assertNotNull("Response from Web Script is null", entity);
        assertEquals("Incorrect Web Script Response", expectedResponse, EntityUtils.toString(entity));
    } finally {
        httpclient.close();
    }
}
 
Example 13
Source File: RestRequestTandemUseSpringRest.java    From activiti-in-action-codes with Apache License 2.0 5 votes vote down vote up
public RestClient(String username, String password) {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
            new AuthScope(null, -1),
            new UsernamePasswordCredentials(username, password));
    HttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));
}
 
Example 14
Source File: APIImportConfigAdapter.java    From apimanager-swagger-promote with Apache License 2.0 5 votes vote down vote up
private void addBasicAuthCredential(String uri, String username, String password,
		HttpClientBuilder httpClientBuilder) {
	if(this.apiConfig instanceof DesiredTestOnlyAPI) return; // Don't do that when unit-testing
	if(username!=null) {
		LOG.info("Loading API-Definition from: " + uri + " ("+username+")");
		CredentialsProvider credsProvider = new BasicCredentialsProvider();
		credsProvider.setCredentials(
	            new AuthScope(AuthScope.ANY),
	            new UsernamePasswordCredentials(username, password));
		httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
	} else {
		LOG.info("Loading API-Definition from: " + uri);
	}
}
 
Example 15
Source File: InfluxDBPublisher.java    From beam with Apache License 2.0 5 votes vote down vote up
private static HttpClientBuilder provideHttpBuilder(final InfluxDBSettings settings) {
  final HttpClientBuilder builder = HttpClientBuilder.create();

  if (isNoneBlank(settings.userName, settings.userPassword)) {
    final CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(
        AuthScope.ANY, new UsernamePasswordCredentials(settings.userName, settings.userPassword));
    builder.setDefaultCredentialsProvider(provider);
  }

  return builder;
}
 
Example 16
Source File: HttpClientManager.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public HttpClientBuilderFacade setCredentials( String user, String password, AuthScope authScope ) {
  CredentialsProvider provider = new BasicCredentialsProvider();
  UsernamePasswordCredentials credentials = new UsernamePasswordCredentials( user, password );
  provider.setCredentials( authScope, credentials );
  this.provider = provider;
  return this;
}
 
Example 17
Source File: SyntheticMonitorService.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private HttpClientContext getHttpClientContext() throws Exception {
    HttpProxyConfig httpProxyConfig = configRepository.getHttpProxyConfig();
    if (httpProxyConfig.host().isEmpty() || httpProxyConfig.username().isEmpty()) {
        return HttpClientContext.create();
    }

    // perform preemptive proxy authentication

    int proxyPort = MoreObjects.firstNonNull(httpProxyConfig.port(), 80);
    HttpHost proxyHost = new HttpHost(httpProxyConfig.host(), proxyPort);

    BasicScheme basicScheme = new BasicScheme();
    basicScheme.processChallenge(new BasicHeader(AUTH.PROXY_AUTH, "BASIC realm="));
    BasicAuthCache authCache = new BasicAuthCache();
    authCache.put(proxyHost, basicScheme);

    String password = httpProxyConfig.encryptedPassword();
    if (!password.isEmpty()) {
        password = Encryption.decrypt(password, configRepository.getLazySecretKey());
    }
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(proxyHost),
            new UsernamePasswordCredentials(httpProxyConfig.username(), password));
    HttpClientContext context = HttpClientContext.create();
    context.setAuthCache(authCache);
    context.setCredentialsProvider(credentialsProvider);
    return context;
}
 
Example 18
Source File: ElasticSearchIndexBootStrapper.java    From ranger with Apache License 2.0 5 votes vote down vote up
private void createClient() {
	try {
		final CredentialsProvider credentialsProvider;
		if (StringUtils.isNotBlank(user)) {
			credentialsProvider = new BasicCredentialsProvider();
			credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
		} else {
			credentialsProvider = null;
		}

		client = new RestHighLevelClient(RestClient
				.builder(EmbeddedServerUtil.toArray(hosts, ",").stream().map(x -> new HttpHost(x, port, protocol))
						.<HttpHost>toArray(i -> new HttpHost[i]))
				.setHttpClientConfigCallback(clientBuilder -> (credentialsProvider != null)
						? clientBuilder.setDefaultCredentialsProvider(credentialsProvider)
						: clientBuilder));
	} catch (Throwable t) {
		lastLoggedAt.updateAndGet(lastLoggedAt -> {
			long now = System.currentTimeMillis();
			long elapsed = now - lastLoggedAt;
			if (elapsed > TimeUnit.MINUTES.toMillis(1)) {
				LOG.severe("Can't connect to ElasticSearch server: " + connectionString() + t);
				return now;
			} else {
				return lastLoggedAt;
			}
		});
	}
}
 
Example 19
Source File: QpidRestAPIQueueCreator.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
private CredentialsProvider getCredentialsProvider(final String managementUser, final String managementPassword)
{
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(managementUser, managementPassword));
    return credentialsProvider;
}
 
Example 20
Source File: ClientBuilderUtils.java    From vividus with Apache License 2.0 4 votes vote down vote up
public static CredentialsProvider createCredentialsProvider(AuthScope authScope, String username, String password)
{
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(authScope, new UsernamePasswordCredentials(username, password));
    return credentialsProvider;
}