Java Code Examples for org.apache.http.client.protocol.HttpClientContext#setCredentialsProvider()

The following examples show how to use org.apache.http.client.protocol.HttpClientContext#setCredentialsProvider() . 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: HopServer.java    From hop with Apache License 2.0 6 votes vote down vote up
private void addCredentials( HttpClientContext context ) {

    String host = environmentSubstitute( hostname );
    int port = Const.toInt( environmentSubstitute( this.port ), 80 );
    String userName = environmentSubstitute( username );
    String password = Encr.decryptPasswordOptionallyEncrypted( environmentSubstitute( this.password ) );
    String proxyHost = environmentSubstitute( proxyHostname );

    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials( userName, password );
    if ( !Utils.isEmpty( proxyHost ) && host.equals( "localhost" ) ) {
      host = "127.0.0.1";
    }
    provider.setCredentials( new AuthScope( host, port ), credentials );
    context.setCredentialsProvider( provider );
    // Generate BASIC scheme object and add it to the local auth cache
    HttpHost target = new HttpHost( host, port, isSslMode() ? HTTPS : HTTP );
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put( target, basicAuth );
    context.setAuthCache( authCache );
  }
 
Example 2
Source File: PentahoParameterRefreshHandler.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * HttpClient does not support preemptive authentication out of the box, because if misused or used incorrectly the
 * preemptive authentication can lead to significant security issues, such as sending user credentials in clear text
 * to an unauthorized third party. Therefore, users are expected to evaluate potential benefits of preemptive
 * authentication versus security risks in the context of their specific application environment.
 *
 * Nonetheless one can configure HttpClient to authenticate preemptively by prepopulating the authentication data cache.
 *
 * @see https://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html
 *
 * @param target target URI
 * @param auth login data
 * @return
 */
private HttpClientContext buildPreemptiveAuthRequestContext( final URI target, final AuthenticationData auth ) {

  if ( target == null || auth == null || StringUtils.isEmpty( auth.getUsername() ) ) {
    return null; // nothing to do here; if no credentials were passed, there's no need to create a preemptive auth Context
  }

  HttpHost targetHost = URIUtils.extractHost( target );

  CredentialsProvider credsProvider = new BasicCredentialsProvider();
  credsProvider.setCredentials( new AuthScope( targetHost.getHostName(), targetHost.getPort() ),
      new UsernamePasswordCredentials( auth.getUsername(), auth.getPassword() ) );

  // 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 );

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

  return context;
}
 
Example 3
Source File: DefaultSpringCloudConfigClientGateway.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private HttpClientContext setupContext() {
    final HttpClientContext context = HttpClientContext.create();
    if (baseUri.contains("@") || springCloudConfigClientConfig.usernameAndPasswordSet()) {
        final AuthCache authCache = InMemoryAuthCache.INSTANCE;
        authCache.put(HttpHost.create(baseUri), new BasicScheme());
        context.setAuthCache(authCache);
        if (springCloudConfigClientConfig.usernameAndPasswordSet()) {
            final CredentialsProvider provider = new BasicCredentialsProvider();
            final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                    springCloudConfigClientConfig.username.get(), springCloudConfigClientConfig.password.get());
            provider.setCredentials(AuthScope.ANY, credentials);
            context.setCredentialsProvider(provider);
        }
    }
    return context;
}
 
Example 4
Source File: ConnectorCommon.java    From nextcloud-java-api with GNU General Public License v3.0 6 votes vote down vote up
private HttpClientContext prepareContext()
{
    HttpHost targetHost = new HttpHost(serverConfig.getServerName(), serverConfig.getPort(), serverConfig.isUseHTTPS() ? "https" : "http");
    AuthCache authCache = new BasicAuthCache();
    authCache.put(targetHost, new BasicScheme());

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials
     = new UsernamePasswordCredentials(serverConfig.getUserName(), serverConfig.getPassword());
    credsProvider.setCredentials(AuthScope.ANY, credentials);

    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
    return context;
}
 
Example 5
Source File: TaxiiHandler.java    From metron with Apache License 2.0 6 votes vote down vote up
private static HttpClientContext createContext(URL endpoint, String username, String password, int port) {
  HttpClientContext context = null;
  HttpHost target = new HttpHost(endpoint.getHost(), port, endpoint.getProtocol());
  if (username != null && password != null) {

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
        new AuthScope(target.getHostName(), target.getPort()),
        new UsernamePasswordCredentials(username, password));

    // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html
    AuthCache authCache = new BasicAuthCache();
    authCache.put(target, new BasicScheme());

    // Add AuthCache to the execution context
    context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
  } else {
    context = null;
  }
  return context;
}
 
Example 6
Source File: HttpPublisher.java    From logsniffer with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Init method for this publisher.
 * 
 * @param velocityRenderer
 *            the velocityRenderer to set
 * @param httpClient
 *            http client
 */
protected void init(final VelocityEventRenderer velocityRenderer,
		final HttpClient httpClient) {
	this.velocityRenderer = velocityRenderer;
	this.httpClient = httpClient;
	if (getHttpAuthentication() != null) {
		CredentialsProvider credsProvider = new BasicCredentialsProvider();
		credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST,
				AuthScope.ANY_PORT), new UsernamePasswordCredentials(
				getHttpAuthentication().getUsername(),
				getHttpAuthentication().getPassword()));
		// Add AuthCache to the execution context
		HttpClientContext context = HttpClientContext.create();
		context.setCredentialsProvider(credsProvider);
	}
}
 
Example 7
Source File: ApacheUtils.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private static void addPreemptiveAuthenticationProxy(HttpClientContext clientContext,
                                                     ProxyConfiguration proxyConfiguration) {

    if (proxyConfiguration.preemptiveBasicAuthenticationEnabled()) {
        HttpHost targetHost = new HttpHost(proxyConfiguration.host(), proxyConfiguration.port());
        CredentialsProvider credsProvider = newProxyCredentialsProvider(proxyConfiguration);
        // 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);

        clientContext.setCredentialsProvider(credsProvider);
        clientContext.setAuthCache(authCache);
    }
}
 
Example 8
Source File: FormatClientSupport.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
protected CloseableHttpResponse execute(final HttpUriRequest request, String username, String password)
    throws IOException
{
  log.debug("Authorizing request for {} using credentials provided for username: {}",
      request.getURI(), username);
  CredentialsProvider credsProvider = new BasicCredentialsProvider();
  credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

  HttpHost host = URIUtils.extractHost(request.getURI());

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

  HttpClientContext clientContext = new HttpClientContext(httpClientContext);
  clientContext.setAuthCache(authCache);
  clientContext.setCredentialsProvider(credsProvider);

  return execute(request, clientContext);
}
 
Example 9
Source File: FormatClientSupport.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
protected CloseableHttpResponse execute(final HttpUriRequest request, String username, String password)
    throws IOException
{
  log.debug("Authorizing request for {} using credentials provided for username: {}",
      request.getURI(), username);
  CredentialsProvider credsProvider = new BasicCredentialsProvider();
  credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

  HttpHost host = URIUtils.extractHost(request.getURI());

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

  HttpClientContext clientContext = new HttpClientContext(httpClientContext);
  clientContext.setAuthCache(authCache);
  clientContext.setCredentialsProvider(credsProvider);

  return execute(request, clientContext);
}
 
Example 10
Source File: HttpEndpoint.java    From Brutusin-RPC with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        HttpClientContextFactory ctxFact = new HttpClientContextFactory() {
            public HttpClientContext create() {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(
                        new AuthScope("localhost", 8080, AuthScope.ANY_REALM, "basic"),
                        new UsernamePasswordCredentials("user", "password"));
                HttpClientContext context = HttpClientContext.create();
                context.setCredentialsProvider(credsProvider);
                return context;
            }
        };

        HttpEndpoint endpoint = new HttpEndpoint(new URI("http://localhost:8080/rpc/http"), ctxFact);

        HttpResponse resp = endpoint.exec("rpc.http.version", null, null);
        if (resp.isIsBinary()) {
            System.out.println("binary");
            System.out.println(resp.getInputStream().getName());
        } else {
            System.out.println(resp.getRpcResponse().getResult());
        }
    }
 
Example 11
Source File: SlaveServer.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private void addCredentials( HttpClientContext context ) {
  String userName;
  String password;
  String host;
  int port;
  String proxyHost;
  lock.readLock().lock();
  try {
    host = environmentSubstitute( hostname );
    port = Const.toInt( environmentSubstitute( this.port ), 80 );
    userName = environmentSubstitute( username );
    password = Encr.decryptPasswordOptionallyEncrypted( environmentSubstitute( this.password ) );
    proxyHost = environmentSubstitute( proxyHostname );
  } finally {
    lock.readLock().unlock();
  }
  CredentialsProvider provider = new BasicCredentialsProvider();
  UsernamePasswordCredentials credentials = new UsernamePasswordCredentials( userName, password );
  if ( !Utils.isEmpty( proxyHost ) && host.equals( "localhost" ) ) {
    host = "127.0.0.1";
  }
  provider.setCredentials( new AuthScope( host, port ), credentials );
  context.setCredentialsProvider( provider );
  // Generate BASIC scheme object and add it to the local auth cache
  HttpHost target = new HttpHost( host, port, isSslMode() ? HTTPS : HTTP );
  AuthCache authCache = new BasicAuthCache();
  BasicScheme basicAuth = new BasicScheme();
  authCache.put( target, basicAuth );
  context.setAuthCache( authCache );
}
 
Example 12
Source File: ContextBuilder.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
public HttpClientContext build() {
    if (StringUtils.isEmpty(preemptiveAuth)) {
        preemptiveAuth = "true";
    }
    HttpClientContext context = HttpClientContext.create();
    if (authTypes.size() == 1 && Boolean.parseBoolean(preemptiveAuth) && !authTypes.contains(AuthTypes.ANONYMOUS)) {
        AuthCache authCache = new BasicAuthCache();
        authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()),
                authSchemeLookup.lookup(authTypes.iterator().next()).create(context));
        context.setCredentialsProvider(credentialsProvider);
        context.setAuthCache(authCache);
    }
    return context;
}
 
Example 13
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 14
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 15
Source File: Http4FileProvider.java    From commons-vfs with Apache License 2.0 4 votes vote down vote up
/**
 * Create an {@link HttpClientContext} object for an http4 file system.
 *
 * @param builder Configuration options builder for http4 provider
 * @param rootName The root path
 * @param fileSystemOptions The FileSystem options
 * @param authData The {@code UserAuthentiationData} object
 * @return an {@link HttpClientContext} object
 * @throws FileSystemException if an error occurs
 */
protected HttpClientContext createHttpClientContext(final Http4FileSystemConfigBuilder builder,
        final GenericFileName rootName, final FileSystemOptions fileSystemOptions,
        final UserAuthenticationData authData) throws FileSystemException {

    final HttpClientContext clientContext = HttpClientContext.create();
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    clientContext.setCredentialsProvider(credsProvider);

    final String username = UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
            UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(rootName.getUserName())));
    final String password = UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
            UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(rootName.getPassword())));

    if (username != null && !username.isEmpty()) {
        credsProvider.setCredentials(new AuthScope(rootName.getHostName(), AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));
    }

    final HttpHost proxyHost = getProxyHttpHost(builder, fileSystemOptions);

    if (proxyHost != null) {
        final UserAuthenticator proxyAuth = builder.getProxyAuthenticator(fileSystemOptions);

        if (proxyAuth != null) {
            final UserAuthenticationData proxyAuthData = UserAuthenticatorUtils.authenticate(proxyAuth,
                    new UserAuthenticationData.Type[] { UserAuthenticationData.USERNAME,
                            UserAuthenticationData.PASSWORD });

            if (proxyAuthData != null) {
                final UsernamePasswordCredentials proxyCreds = new UsernamePasswordCredentials(
                        UserAuthenticatorUtils.toString(
                                UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME, null)),
                        UserAuthenticatorUtils.toString(
                                UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD, null)));

                credsProvider.setCredentials(new AuthScope(proxyHost.getHostName(), AuthScope.ANY_PORT),
                        proxyCreds);
            }

            if (builder.isPreemptiveAuth(fileSystemOptions)) {
                final AuthCache authCache = new BasicAuthCache();
                final BasicScheme basicAuth = new BasicScheme();
                authCache.put(proxyHost, basicAuth);
                clientContext.setAuthCache(authCache);
            }
        }
    }

    return clientContext;
}
 
Example 16
Source File: OssIndexHttpClient.java    From ossindex-gradle-plugin with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Perform the request with the given URL and JSON data.
 *
 * @param requestString Server request relative URL
 * @param data          JSON data for the request
 * @return JSON results of the request
 * @throws IOException On query problems
 */
public String performPostRequest(String requestString, String data) throws IOException {
  HttpPost request = new HttpPost(getBaseUrl() + requestString);
  String json = null;

  request.setHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE));
  request.setHeader(new BasicHeader(HttpHeaders.ACCEPT, CONTENT_TYPE));
  request.setHeader(new BasicHeader(HttpHeaders.CONTENT_ENCODING, CONTENT_TYPE));

  HttpClientBuilder httpClientBuilder = HttpClients.custom()
      .setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build());

  final HttpClientContext context = HttpClientContext.create();
  if (credentials != null) {
    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, credentials);

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

    // Add AuthCache to the execution context
    context.setCredentialsProvider(provider);
    context.setAuthCache(authCache);
  }

  CloseableHttpClient httpClient = httpClientBuilder.build();
  if (proxies.size() > 0) {
    // We only check the first proxy for now
    Proxy myProxy = proxies.get(0);
    HttpHost proxy = myProxy.getHttpHost();
    RequestConfig config = RequestConfig.custom()
        .setProxy(proxy)
        .setSocketTimeout(myProxy.getProxySocketTimeout())
        .setConnectTimeout(myProxy.getProxyConnectTimeout())
        .setConnectionRequestTimeout(myProxy.getProxyConnectionRequestTimeout())
        .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
        .build();
    request.setConfig(config);
  }
  try {
    logger.debug("------------------------------------------------");
    logger.debug("OSS Index POST: " + getBaseUrl() + requestString);
    logger.debug(data);
    logger.debug("------------------------------------------------");

    request.setEntity(new StringEntity(data));
    CloseableHttpResponse response = httpClient.execute(request, context);
    int code = response.getStatusLine().getStatusCode();
    if (code < 200 || code > 299) {
      throw new ConnectException(response.getStatusLine().getReasonPhrase() + " (" + code + ")");
    }
    json = EntityUtils.toString(response.getEntity(), "UTF-8");
  }
  catch (ParseException e) {
    throw new IOException(e);
  }
  finally {
    httpClient.close();
  }
  return json;
}
 
Example 17
Source File: GatewayBasicFuncTest.java    From knox with Apache License 2.0 4 votes vote down vote up
private String oozieSubmitJob( String user, String password, String request, int status ) throws IOException, URISyntaxException {
    driver.getMock( "OOZIE" )
        .expect()
        .method( "POST" )
        .pathInfo( "/v1/jobs" )
        .respond()
        .status( HttpStatus.SC_CREATED )
        .content( driver.getResourceBytes( "oozie-jobs-submit-response.json" ) )
        .contentType( "application/json" );
    URL url = new URL( driver.getUrl( "OOZIE" ) + "/v1/jobs?action=start" + ( 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 );

    HttpPost post = new HttpPost( url.toURI() );
//      post.getParams().setParameter( "action", "start" );
    StringEntity entity = new StringEntity( request, org.apache.http.entity.ContentType.create( "application/xml", StandardCharsets.UTF_8.name() ) );
    post.setEntity( entity );
    post.setHeader( "X-XSRF-Header", "ksdjfhdsjkfhds" );
    HttpResponse response = client.execute( targetHost, post, context );
    assertThat( response.getStatusLine().getStatusCode(), Matchers.is(status) );
    String json = EntityUtils.toString( response.getEntity() );

//      String json = given()
//          .log().all()
//          .auth().preemptive().basic( user, password )
//          .queryParam( "action", "start" )
//          .contentType( "application/xml;charset=UTF-8" )
//          .content( request )
//          .then()
//          .log().all()
//          .statusCode( status )
//          .when().post( getUrl( "OOZIE" ) + "/v1/jobs" + ( isUseGateway() ? "" : "?user.name=" + user ) ).asString();
    return JsonPath.from(json).getString( "id" );
  }
 
Example 18
Source File: HttpClientAdvancedConfigurationIntegrationTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException {
    //given
    proxyMock.stubFor(get(urlMatching("/private"))
      .willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
    serviceMock.stubFor(get(urlEqualTo("/private"))
      .willReturn(aResponse().withStatus(200)));


    HttpHost proxy = new HttpHost("localhost", 8090);
    DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);

    // Client credentials
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(proxy),
      new UsernamePasswordCredentials("username_admin", "secret_password"));


    // 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(proxy, basicAuth);
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthCache(authCache);


    HttpClient httpclient = HttpClients.custom()
      .setRoutePlanner(routePlanner)
      .setDefaultCredentialsProvider(credentialsProvider)
      .build();


    //when
    final HttpGet httpGet = new HttpGet("http://localhost:8089/private");
    HttpResponse response = httpclient.execute(httpGet, context);

    //then
    assertEquals(response.getStatusLine().getStatusCode(), 200);
    proxyMock.verify(getRequestedFor(urlEqualTo("/private")).withHeader("Authorization", containing("Basic")));
    serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
}
 
Example 19
Source File: JenKinsBuildService.java    From ehousechina with Apache License 2.0 4 votes vote down vote up
private HttpClientContext getHttpClientContext(){
	HttpClientContext httpClientContext = HttpClientContext.create();
	httpClientContext.setCredentialsProvider(this.getCredentialsProvider());
	httpClientContext.setAuthCache(this.getAuthCache());
	return httpClientContext;
}
 
Example 20
Source File: HttpRestWb.java    From document-management-software with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static void uploadDocument(CloseableHttpClient httpclient) throws IOException {

		System.out.println("uploadDocument(CloseableHttpClient)");
		
		URL url = new URL(BASE_PATH);
		
		HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
		CredentialsProvider credsProvider = new BasicCredentialsProvider();
		credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin"));
        
        AuthCache authCache = new BasicAuthCache();
        authCache.put(targetHost, new BasicScheme());
        
		// Add AuthCache to the execution context
		HttpClientContext context = HttpClientContext.create();
		context.setCredentialsProvider(credsProvider);
		context.setAuthCache(authCache);
		
        HttpPost httppost = new HttpPost(BASE_PATH + "/services/rest/document/upload");
       
        File file = new File("c:/users/shatz/Downloads/logicaldocsecurity-171122130133.pdf");
        //File file = new File("C:/tmp/InvoiceProcessing01-workflow.png");  
                
		System.out.println(file.getName());	
		System.out.println(file.getAbsolutePath());	
		
		long folderID = 124358812L;
		
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();         
		builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
		builder.addTextBody("filename", file.getName(), ContentType.TEXT_PLAIN);
		builder.addBinaryBody("filedata", file, ContentType.DEFAULT_BINARY, file.getName());
		builder.addTextBody("folderId", Long.toString(folderID), ContentType.TEXT_PLAIN);		
		
		// 
		HttpEntity entity = builder.build();
		httppost.setEntity(entity);
		
		CloseableHttpResponse response = httpclient.execute(httppost, context);
		
		int code = response.getStatusLine().getStatusCode();
		System.out.println("HTTPstatus code: "+ code);
		
		try {
			HttpEntity rent = response.getEntity();
			if (rent != null) {
				String respoBody = EntityUtils.toString(rent, "UTF-8");
				System.out.println(respoBody);
			}
		} finally {
			response.close();
		}
	}