org.apache.http.client.AuthCache Java Examples

The following examples show how to use org.apache.http.client.AuthCache. 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: 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 #2
Source File: HttpClientUtil.java    From hop with Apache License 2.0 6 votes vote down vote up
/**
 * Returns context with AuthCache or null in case of any exception was thrown.
 *
 * @param host
 * @param port
 * @param user
 * @param password
 * @param schema
 * @return {@link org.apache.http.client.protocol.HttpClientContext HttpClientContext}
 */
public static HttpClientContext createPreemptiveBasicAuthentication( String host, int port, String user,
                                                                     String password, String schema ) {
  HttpClientContext localContext = null;
  try {
    HttpHost target = new HttpHost( host, port, schema );
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
      new AuthScope( target.getHostName(), target.getPort() ),
      new UsernamePasswordCredentials( user, 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( target, basicAuth );

    // Add AuthCache to the execution context
    localContext = HttpClientContext.create();
    localContext.setAuthCache( authCache );
  } catch ( Exception e ) {
    return null;
  }
  return localContext;
}
 
Example #3
Source File: Substitute_RestClient.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Substitute
public synchronized void setNodes(Collection<Node> nodes) {
    if (nodes == null || nodes.isEmpty()) {
        throw new IllegalArgumentException("nodes must not be null or empty");
    }
    AuthCache authCache = new NoSerializationBasicAuthCache();

    Map<HttpHost, Node> nodesByHost = new LinkedHashMap<>();
    for (Node node : nodes) {
        Objects.requireNonNull(node, "node cannot be null");
        // TODO should we throw an IAE if we have two nodes with the same host?
        nodesByHost.put(node.getHost(), node);
        authCache.put(node.getHost(), new BasicScheme());
    }
    this.nodeTuple = new NodeTuple<>(Collections.unmodifiableList(new ArrayList<>(nodesByHost.values())),
            authCache);
    this.blacklist.clear();
}
 
Example #4
Source File: HttpComponentsClientHttpRequestFactoryDigestAuth.java    From tutorials with MIT License 6 votes vote down vote up
private HttpContext createHttpContext() {
    // Create AuthCache instance
    final AuthCache authCache = new BasicAuthCache();
    // Generate DIGEST scheme object, initialize it and add it to the local auth cache
    final DigestScheme digestAuth = new DigestScheme();
    // If we already know the realm name
    digestAuth.overrideParamter("realm", "Custom Realm Name");

    // digestAuth.overrideParamter("nonce", "MTM3NTU2OTU4MDAwNzoyYWI5YTQ5MTlhNzc5N2UxMGM5M2Y5M2ViOTc4ZmVhNg==");
    authCache.put(host, digestAuth);

    // Add AuthCache to the execution context
    final BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
    return localcontext;
}
 
Example #5
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 #6
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 #7
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 #8
Source File: HttpClientUtil.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
/**
 * Returns context with AuthCache or null in case of any exception was thrown.
 *
 * @param host
 * @param port
 * @param user
 * @param password
 * @param schema
 * @return {@link org.apache.http.client.protocol.HttpClientContext HttpClientContext}
 */
public static HttpClientContext createPreemptiveBasicAuthentication( String host, int port, String user,
                                                                     String password, String schema ) {
  HttpClientContext localContext = null;
  try {
    HttpHost target = new HttpHost( host, port, schema );
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
      new AuthScope( target.getHostName(), target.getPort() ),
      new UsernamePasswordCredentials( user, 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( target, basicAuth );

    // Add AuthCache to the execution context
    localContext = HttpClientContext.create();
    localContext.setAuthCache( authCache );
  } catch ( Exception e ) {
    return null;
  }
  return localContext;
}
 
Example #9
Source File: HttpClientUtil.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Returns context with AuthCache or null in case of any exception was thrown.
 *
 * @param host
 * @param port
 * @param user
 * @param password
 * @param schema
 * @return {@link org.apache.http.client.protocol.HttpClientContext HttpClientContext}
 */
public static HttpClientContext createPreemptiveBasicAuthentication( String host, int port, String user,
                                                                     String password, String schema ) {
  HttpClientContext localContext = null;
  try {
    HttpHost target = new HttpHost( host, port, schema );
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
      new AuthScope( target.getHostName(), target.getPort() ),
      new UsernamePasswordCredentials( user, 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( target, basicAuth );

    // Add AuthCache to the execution context
    localContext = HttpClientContext.create();
    localContext.setAuthCache( authCache );
  } catch ( Exception e ) {
    return null;
  }
  return localContext;
}
 
Example #10
Source File: ApacheUtils.java    From ibm-cos-sdk-java with Apache License 2.0 6 votes vote down vote up
private static void addPreemptiveAuthenticationProxy(HttpClientContext clientContext,
                                                     HttpClientSettings settings) {

    if (settings.isPreemptiveBasicProxyAuth()) {
        HttpHost targetHost = new HttpHost(settings.getProxyHost(), settings
                .getProxyPort());
        final CredentialsProvider credsProvider = newProxyCredentialsProvider(settings);
        // 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 #11
Source File: SPARQLProtocolSession.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected void setUsernameAndPasswordForUrl(String username, String password, String url) {

		if (username != null && password != null) {
			logger.debug("Setting username '{}' and password for server at {}.", username, url);
			java.net.URI requestURI = java.net.URI.create(url);
			String host = requestURI.getHost();
			int port = requestURI.getPort();
			AuthScope scope = new AuthScope(host, port);
			UsernamePasswordCredentials cred = new UsernamePasswordCredentials(username, password);
			CredentialsProvider credsProvider = new BasicCredentialsProvider();
			credsProvider.setCredentials(scope, cred);
			httpContext.setCredentialsProvider(credsProvider);
			AuthCache authCache = new BasicAuthCache();
			BasicScheme basicAuth = new BasicScheme();
			HttpHost httpHost = new HttpHost(requestURI.getHost(), requestURI.getPort(), requestURI.getScheme());
			authCache.put(httpHost, basicAuth);
			httpContext.setAuthCache(authCache);
		} else {
			httpContext.removeAttribute(HttpClientContext.AUTH_CACHE);
			httpContext.removeAttribute(HttpClientContext.CREDS_PROVIDER);
		}
	}
 
Example #12
Source File: WireMockTestClient.java    From wiremock-webhooks-extension with Apache License 2.0 6 votes vote down vote up
public WireMockResponse getWithPreemptiveCredentials(String url, int port, String username, String password) {
    HttpHost target = new HttpHost("localhost", port);
    HttpClient httpClient = httpClientWithPreemptiveAuth(target, username, password);

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(target, basicAuth);
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    try {
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpClient.execute(target, httpget, localContext);
        return new WireMockResponse(response);
    } catch (IOException e) {
        return throwUnchecked(e, WireMockResponse.class);
    }
}
 
Example #13
Source File: HttpRpcTransport.java    From etherjar with Apache License 2.0 6 votes vote down vote up
/**
 * Setup Basic Auth for RPC calls
 *
 * @param username username
 * @param password password
 * @return builder
 */
public Builder basicAuth(String username, String password) {
    this.httpClient = null;

    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    AuthCache cache = new BasicAuthCache();
    cache.put(
        new HttpHost(target.getHost(), target.getPort(), target.getScheme()),
        new BasicScheme()
    );

    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(provider);
    context.setAuthCache(cache);
    this.context = context;

    return this;
}
 
Example #14
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 #15
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 #16
Source File: GeoServerIT.java    From geowave with Apache License 2.0 6 votes vote down vote up
protected static Pair<CloseableHttpClient, HttpClientContext> createClientAndContext() {
  final CredentialsProvider provider = new BasicCredentialsProvider();
  provider.setCredentials(
      new AuthScope("localhost", ServicesTestEnvironment.JETTY_PORT),
      new UsernamePasswordCredentials(
          ServicesTestEnvironment.GEOSERVER_USER,
          ServicesTestEnvironment.GEOSERVER_PASS));
  final AuthCache authCache = new BasicAuthCache();
  final HttpHost targetHost =
      new HttpHost("localhost", ServicesTestEnvironment.JETTY_PORT, "http");
  authCache.put(targetHost, new BasicScheme());

  // Add AuthCache to the execution context
  final HttpClientContext context = HttpClientContext.create();
  context.setCredentialsProvider(provider);
  context.setAuthCache(authCache);
  return ImmutablePair.of(
      HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build(),
      context);
}
 
Example #17
Source File: HDInsightInstance.java    From reef with Apache License 2.0 6 votes vote down vote up
private HttpClientContext getClientContext(final String hostname, final String username, final String password)
    throws IOException {
  final HttpHost targetHost = new HttpHost(hostname, 443, "https");
  final HttpClientContext result = HttpClientContext.create();

  // Setup credentials provider
  final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

  credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
  result.setCredentialsProvider(credentialsProvider);

  // Setup preemptive authentication
  final AuthCache authCache = new BasicAuthCache();
  final BasicScheme basicAuth = new BasicScheme();
  authCache.put(targetHost, basicAuth);
  result.setAuthCache(authCache);
  final HttpGet httpget = new HttpGet("/");

  // Prime the cache
  try (CloseableHttpResponse response = this.httpClient.execute(targetHost, httpget, result)) {
    // empty try block used to automatically close resources
  }
  return result;
}
 
Example #18
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 #19
Source File: TestSecureRESTServer.java    From hbase with Apache License 2.0 6 votes vote down vote up
private Pair<CloseableHttpClient,HttpClientContext> getClient() {
  HttpClientConnectionManager pool = new PoolingHttpClientConnectionManager();
  HttpHost host = new HttpHost("localhost", REST_TEST.getServletPort());
  Registry<AuthSchemeProvider> authRegistry =
      RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO,
          new SPNegoSchemeFactory(true, true)).build();
  CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(AuthScope.ANY, EmptyCredentials.INSTANCE);
  AuthCache authCache = new BasicAuthCache();

  CloseableHttpClient client = HttpClients.custom()
      .setDefaultAuthSchemeRegistry(authRegistry)
      .setConnectionManager(pool).build();

  HttpClientContext context = HttpClientContext.create();
  context.setTargetHost(host);
  context.setCredentialsProvider(credentialsProvider);
  context.setAuthSchemeRegistry(authRegistry);
  context.setAuthCache(authCache);

  return new Pair<>(client, context);
}
 
Example #20
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 #21
Source File: HttpComponentsClientHttpRequestFactoryBasicAuth.java    From tutorials with MIT License 5 votes vote down vote up
private HttpContext createHttpContext() {

        AuthCache authCache = new BasicAuthCache();

        BasicScheme basicAuth = new BasicScheme();
        authCache.put(host, basicAuth);

        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
        return localcontext;
    }
 
Example #22
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 #23
Source File: HttpHelper.java    From sputnik with Apache License 2.0 5 votes vote down vote up
@NotNull
public HttpClientContext buildClientContext(@NotNull HttpHost httpHost, @NotNull AuthScheme authScheme) {
    AuthCache basicAuthCache = new BasicAuthCache();
    basicAuthCache.put(httpHost, authScheme);
    HttpClientContext httpClientContext = HttpClientContext.create();
    httpClientContext.setAuthCache(basicAuthCache);
    httpClientContext.setTargetHost(httpHost);
    return httpClientContext;
}
 
Example #24
Source File: DigestAuthHandler.java    From restfiddle with Apache License 2.0 5 votes vote down vote up
public HttpClientContext preemptive() {
AuthCache authCache = new BasicAuthCache();

DigestScheme digestAuth = new DigestScheme();

digestAuth.overrideParamter("realm", "");
digestAuth.overrideParamter("nonce", "");

// TODO : Add target
// authCache.put(target, digestAuth);
HttpClientContext localContext = HttpClientContext.create();
localContext.setAuthCache(authCache);

return localContext;
   }
 
Example #25
Source File: BceHttpClient.java    From bce-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates HttpClient Context object based on the internal request.
 *
 * @param request The internal request.
 * @return HttpClient Context object.
 */
protected HttpClientContext createHttpContext(InternalRequest request) {
    HttpClientContext context = HttpClientContext.create();
    context.setRequestConfig(this.requestConfigBuilder.setExpectContinueEnabled(request.isExpectContinueEnabled())
            .setSocketTimeout(this.config.getSocketTimeoutInMillis()).build());
    if (this.credentialsProvider != null) {
        context.setCredentialsProvider(this.credentialsProvider);
    }
    if (this.config.isProxyPreemptiveAuthenticationEnabled()) {
        AuthCache authCache = new BasicAuthCache();
        authCache.put(this.proxyHttpHost, new BasicScheme());
        context.setAuthCache(authCache);
    }
    return context;
}
 
Example #26
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 #27
Source File: SlaveServerTest.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthCredentialsSchemeWithoutSSL() {
  slaveServer.setUsername( "admin" );
  slaveServer.setPassword( "password" );
  slaveServer.setHostname( "localhost" );
  slaveServer.setPort( "8080" );
  slaveServer.setSslMode( false );

  AuthCache cache = slaveServer.getAuthContext().getAuthCache();
  assertNull( cache.get( new HttpHost( "localhost", 8080, "https" ) ) );
  assertNotNull( cache.get( new HttpHost( "localhost", 8080, "http" ) ) );
}
 
Example #28
Source File: HTTPClient.java    From gocd-build-status-notifier with Apache License 2.0 5 votes vote down vote up
public void postRequest(String updateURL, AuthenticationType authenticationType, String username, String password, String requestBody) throws Exception {
    CloseableHttpClient httpClient = null;
    try {
        HttpPost request = new HttpPost(updateURL);
        request.addHeader("content-type", "application/json");
        request.setEntity(new StringEntity(requestBody));

        HttpHost target = getHttpHost(updateURL);
        AuthCache authCache = getAuthCache(authenticationType, target);
        HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(target), new UsernamePasswordCredentials(username, password));
        httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();

        HttpResponse response = httpClient.execute(request, localContext);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode > 204) {
            throw new RuntimeException("Error occurred. Status Code: " + statusCode);
        }
    } finally {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (Exception e) {
                // ignore
            }
        }
    }
}
 
Example #29
Source File: BitcoinJSONRPCRetriever.java    From bitcoin-transaction-explorer with MIT License 5 votes vote down vote up
private void init(final String host, final int port, final String rpcUser, final String rpcPassword) {
  uri = String.format(URI_FORMAT, host, port);
  credentialsProvider.setCredentials(new AuthScope(host, port, JSON_RPC_REALM, AUTH_SCHEME), new UsernamePasswordCredentials(rpcUser, rpcPassword));

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

  localContext = HttpClientContext.create();
  localContext.setAuthCache(authCache);
}
 
Example #30
Source File: WebService.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private HttpClient getHttpClient( HttpClientContext context ) {
  HttpClientManager.HttpClientBuilderFacade clientBuilder = HttpClientManager.getInstance().createBuilder();

  String login = environmentSubstitute( meta.getHttpLogin() );
  if ( StringUtils.isNotBlank( login ) ) {
    clientBuilder.setCredentials( login,
      Encr.decryptPasswordOptionallyEncrypted( environmentSubstitute( meta.getHttpPassword() ) ) );
  }
  int proxyPort = 0;
  if ( StringUtils.isNotBlank( meta.getProxyHost() ) ) {
    proxyPort = Const.toInt( environmentSubstitute( meta.getProxyPort() ), 8080 );
    clientBuilder.setProxy( meta.getProxyHost(), proxyPort );
  }
  CloseableHttpClient httpClient = clientBuilder.build();

  if ( proxyPort != 0 ) {
    // Preemptive authentication
    HttpHost target = new HttpHost( meta.getProxyHost(), proxyPort, "http" );
    // 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( target, basicAuth );
    // Add AuthCache to the execution context
    context.setAuthCache( authCache );
  }

  return httpClient;
}