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

The following examples show how to use org.apache.http.impl.client.BasicCredentialsProvider#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: CMODataAbapClient.java    From devops-cm-client with Apache License 2.0 6 votes vote down vote up
public CMODataAbapClient(String endpoint, String user, String password) throws URISyntaxException {

        this.endpoint = new URI(endpoint);
        this.requestBuilder = new TransportRequestBuilder(this.endpoint);

        // the same instance needs to be used as long as we are in the same session. Hence multiple
        // clients must share the same cookie store. Reason: we are logged on with the first request
        // and get a cookie. That cookie - expressing the user has already been logged in - needs to be
        // present in all subsequent requests.
        CookieStore sessionCookieStore = new BasicCookieStore();

        BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
        basicCredentialsProvider.setCredentials(
                new AuthScope(this.endpoint.getHost(), this.endpoint.getPort()),
                new UsernamePasswordCredentials(user, password));

        this.clientFactory = new HttpClientFactory(sessionCookieStore, basicCredentialsProvider);
    }
 
Example 2
Source File: StandardMattermostService.java    From jenkins-mattermost-plugin with MIT License 6 votes vote down vote up
private void setupProxyAuth(ProxyConfiguration proxy, HttpClientBuilder clientBuilder, HttpHost proxyHost)
{
	String username = proxy.getUserName();
	String password = proxy.getPassword();
	// Consider it to be passed if username specified. Sufficient?
	if (username != null && !username.isEmpty())
	{
		logger.info("Using proxy authentication (user=" + username + ")");
		BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
		basicCredentialsProvider.setCredentials(
				new org.apache.http.auth.AuthScope(proxyHost.getHostName(), proxy.port),
				new org.apache.http.auth.UsernamePasswordCredentials(username, password));

		clientBuilder.setDefaultCredentialsProvider(basicCredentialsProvider);
	}
}
 
Example 3
Source File: VSCrawlerRoutePlanner.java    From vscrawler with Apache License 2.0 5 votes vote down vote up
@Override
protected HttpHost determineProxy(HttpHost host, HttpRequest request, HttpContext context) throws HttpException {
    HttpClientContext httpClientContext = HttpClientContext.adapt(context);
    Proxy proxy = proxyPlanner.determineProxy(host, request, context, ipPool, crawlerSession);

    if (proxy == null) {
        return null;
    }
    if (log.isDebugEnabled()) {
        log.debug("{} 当前使用IP为:{}:{}", host.getHostName(), proxy.getIp(), proxy.getPort());
    }
    context.setAttribute(VSCRAWLER_AVPROXY_KEY, proxy);
    crawlerSession.setExtInfo(VSCRAWLER_AVPROXY_KEY, proxy);

    if (proxy.getAuthenticationHeaders() != null) {
        for (Header header : proxy.getAuthenticationHeaders()) {
            request.addHeader(header);
        }
    }

    if (StringUtils.isNotEmpty(proxy.getUsername()) && StringUtils.isNotEmpty(proxy.getPassword())) {
        BasicCredentialsProvider credsProvider1 = new BasicCredentialsProvider();
        httpClientContext.setCredentialsProvider(credsProvider1);
        credsProvider1.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword()));
    }
    return new HttpHost(proxy.getIp(), proxy.getPort());
}
 
Example 4
Source File: KarafIT.java    From fcrepo-camel-toolbox with Apache License 2.0 5 votes vote down vote up
private String post(final String url) {
    final BasicCredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(FEDORA_USERNAME, FEDORA_PASSWORD));
    final CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(provider).build();

    try {
        final HttpPost httppost = new HttpPost(url);
        final HttpResponse response = httpclient.execute(httppost);
        assertEquals(SC_CREATED, response.getStatusLine().getStatusCode());
        return EntityUtils.toString(response.getEntity(), "UTF-8");
    } catch (final IOException ex) {
        LOGGER.debug("Unable to extract HttpEntity response into an InputStream: ", ex);
        return "";
    }
}
 
Example 5
Source File: RouteIT.java    From fcrepo-camel-toolbox with Apache License 2.0 5 votes vote down vote up
private String post(final String url) {
    final BasicCredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(FEDORA_USERNAME, FEDORA_PASSWORD));
    final CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(provider).build();
    try {
        final HttpPost httppost = new HttpPost(url);
        final HttpResponse response = httpclient.execute(httppost);
        assertEquals(SC_CREATED, response.getStatusLine().getStatusCode());
        return EntityUtils.toString(response.getEntity(), "UTF-8");
    } catch (final IOException ex) {
        LOGGER.debug("Unable to extract HttpEntity response into an InputStream: ", ex);
        return "";
    }
}
 
Example 6
Source File: YarnClient.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private static HttpClient buildSpengoHttpClient() {
  HttpClientBuilder builder = HttpClientBuilder.create();
  Lookup<AuthSchemeProvider> authSchemeRegistry
      = RegistryBuilder.<AuthSchemeProvider>create().register(
          AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();
  builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
  BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(new AuthScope(null, -1, null), new Credentials() {
    @Override
    public Principal getUserPrincipal() {
      return null;
    }

    @Override
    public String getPassword() {
      return null;
    }
  });
  builder.setDefaultCredentialsProvider(credentialsProvider);

  // Avoid output WARN: Cookie rejected
  RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES)
      .build();
  builder.setDefaultRequestConfig(globalConfig);

  CloseableHttpClient httpClient = builder.build();

  return httpClient;
}
 
Example 7
Source File: ElasticSearchSink.java    From pulsar with Apache License 2.0 5 votes vote down vote up
private CredentialsProvider getCredentialsProvider() {

        if (StringUtils.isEmpty(elasticSearchConfig.getUsername())
            || StringUtils.isEmpty(elasticSearchConfig.getPassword())) {
            return null;
        }

        credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(elasticSearchConfig.getUsername(),
                        elasticSearchConfig.getPassword()));
        return credentialsProvider;
    }
 
Example 8
Source File: HttpBuilderConfigurationTest.java    From FcmJava with MIT License 5 votes vote down vote up
@Test
public void testFcmClientWithProxySettings() throws Exception {

    // Create Settings:
    IFcmClientSettings settings = new FakeFcmClientSettings();

    // Define the Credentials to be used:
    BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();

    // Set the Credentials (any auth scope used):
    basicCredentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("your_username", "your_password"));

    // Create the Apache HttpClientBuilder:
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create()
            // Set the Proxy Address:
            .setProxy(new HttpHost("your_hostname", 1234))
            // Set the Authentication Strategy:
            .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy())
            // Set the Credentials Provider we built above:
            .setDefaultCredentialsProvider(basicCredentialsProvider);

    // Create the DefaultHttpClient:
    DefaultHttpClient httpClient = new DefaultHttpClient(settings, httpClientBuilder);

    // Finally build the FcmClient:
    try(IFcmClient client = new FcmClient(settings, httpClient)) {
        // TODO Work with the Proxy ...
    }
}
 
Example 9
Source File: HttpDataService.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void setAuthentication(Map<String, Object> parameters, HttpClientBuilder clientBuilder)
{
	String username = getUsername(parameters);
	if (username != null)
	{
		String password = getPassword(parameters);
		
		BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
		//FIXME proxy authentication?
		credentialsProvider.setCredentials(
				new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), 
				new UsernamePasswordCredentials(username, password));
		clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
	}
}
 
Example 10
Source File: MCRDataciteClient.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
private BasicCredentialsProvider getCredentialsProvider() {
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    if (userName != null && !userName.isEmpty() && password != null && !password.isEmpty()) {
        credentialsProvider.setCredentials(AuthScope.ANY, getCredentials());
    }

    return credentialsProvider;
}
 
Example 11
Source File: BasicCredentials.java    From log4j2-elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void applyTo(HttpClientFactory.Builder builder) {

    BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
    basicCredentialsProvider.setCredentials(
            AuthScope.ANY,
            new UsernamePasswordCredentials(username, password)
    );

    builder.withDefaultCredentialsProvider(basicCredentialsProvider);

}
 
Example 12
Source File: BasicCredentials.java    From log4j2-elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void applyTo(HttpClientConfig.Builder builder) {

    BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
    basicCredentialsProvider.setCredentials(
            AuthScope.ANY,
            new UsernamePasswordCredentials(username, password)
    );

    builder.credentialsProvider(basicCredentialsProvider);

}
 
Example 13
Source File: HttpClientUtils.java    From spring-cloud-dashboard with Apache License 2.0 5 votes vote down vote up
/**
 * Ensures that the passed-in {@link RestTemplate} is using the Apache HTTP Client. If the optional {@code username} AND
 * {@code password} are not empty, then a {@link BasicCredentialsProvider} will be added to the {@link CloseableHttpClient}.
 *
 * Furthermore, you can set the underlying {@link SSLContext} of the {@link HttpClient} allowing you to accept self-signed
 * certificates.
 *
 * @param restTemplate Must not be null
 * @param username Can be null
 * @param password Can be null
 * @param skipSslValidation Use with caution! If true certificate warnings will be ignored.
 */
public static void prepareRestTemplate(
		RestTemplate restTemplate,
		String username,
		String password,
		boolean skipSslValidation) {

	Assert.notNull(restTemplate, "The provided RestTemplate must not be null.");

	final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

	if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
		final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
		credentialsProvider.setCredentials(AuthScope.ANY,
				new UsernamePasswordCredentials(
						username,
						password));
		httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
	}

	if (skipSslValidation) {
		httpClientBuilder.setSSLContext(HttpClientUtils.buildCertificateIgnoringSslContext());
		httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
	}

	final CloseableHttpClient httpClient = httpClientBuilder.build();
	final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
	restTemplate.setRequestFactory(requestFactory);
}
 
Example 14
Source File: RestUtil.java    From cf-java-client-sap with Apache License 2.0 5 votes vote down vote up
public ClientHttpRequestFactory createRequestFactory(HttpProxyConfiguration httpProxyConfiguration, boolean trustSelfSignedCerts) {
    HttpClientBuilder httpClientBuilder = HttpClients.custom()
                                                     .useSystemProperties();

    if (trustSelfSignedCerts) {
        httpClientBuilder.setSslcontext(buildSslContext());
        httpClientBuilder.setHostnameVerifier(BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    }

    if (httpProxyConfiguration != null) {
        HttpHost proxy = new HttpHost(httpProxyConfiguration.getProxyHost(), httpProxyConfiguration.getProxyPort());
        httpClientBuilder.setProxy(proxy);

        if (httpProxyConfiguration.isAuthRequired()) {
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(httpProxyConfiguration.getProxyHost(),
                                                             httpProxyConfiguration.getProxyPort()),
                                               new UsernamePasswordCredentials(httpProxyConfiguration.getUsername(),
                                                                               httpProxyConfiguration.getPassword()));
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }

        HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        httpClientBuilder.setRoutePlanner(routePlanner);
    }

    HttpClient httpClient = httpClientBuilder.build();

    return new HttpComponentsClientHttpRequestFactory(httpClient);
}
 
Example 15
Source File: HttpClientConfigurer.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
public HttpClientConfigurer basicAuthCredentials(String username, String password) {
	final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
	credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
	httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

	useBasicAuth = true;

	return this;
}
 
Example 16
Source File: TestHttpClient4.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
private CredentialsProvider getProxyCredentialProvider() {
    String proxyHost = Settings.getProperty("davmail.proxyHost");
    int proxyPort = Settings.getIntProperty("davmail.proxyPort");

    // proxy authentication
    String proxyUser = Settings.getProperty("davmail.proxyUser");
    String proxyPassword = Settings.getProperty("davmail.proxyPassword");
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    AuthScope authScope = new AuthScope(proxyHost, proxyPort, AuthScope.ANY_REALM);
    credentialsProvider.setCredentials(authScope, new UsernamePasswordCredentials(proxyUser, proxyPassword));
    return credentialsProvider;
}
 
Example 17
Source File: SiteToSiteRestApiClient.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private void setupCredentialsProvider() {
    credentialsProvider = new BasicCredentialsProvider();
    if (proxy != null) {
        if (!isEmpty(proxy.getUsername()) && !isEmpty(proxy.getPassword())) {
            credentialsProvider.setCredentials(
                new AuthScope(proxy.getHttpHost()),
                new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword()));
        }

    }
}
 
Example 18
Source File: WebApiTestServer.java    From baleen with Apache License 2.0 5 votes vote down vote up
public static CloseableHttpClient createClient(String username, String password) {
  HttpClientBuilder builder = HttpClientBuilder.create();

  if (username != null && password != null) {
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(
        AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    builder.setDefaultCredentialsProvider(credentialsProvider);
  }

  return builder.build();
}
 
Example 19
Source File: RestUtils.java    From directory-fortress-core with Apache License 2.0 4 votes vote down vote up
private CredentialsProvider getCredentialProvider(String uid, String password) {
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials( new AuthScope( httpHost,Integer.valueOf( httpPort )),
        new UsernamePasswordCredentials(uid==null? httpUid :uid,password==null? httpPw :password) );
    return credentialsProvider;
}
 
Example 20
Source File: HttpClientUtil.java    From DataLink with Apache License 2.0 4 votes vote down vote up
public static void setBasicAuth(String username, String password) {
    provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(username,password));
}