Java Code Examples for org.apache.http.client.AuthCache#put()

The following examples show how to use org.apache.http.client.AuthCache#put() . 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: 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 2
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 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: 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 5
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 6
Source File: LocalFileModel.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public LocalFileModel( final String url,
                       final HttpClientManager.HttpClientBuilderFacade clientBuilder,
                       final String username,
                       final String password,
                       final String hostName,
                       int port ) {

  if ( url == null ) {
    throw new NullPointerException();
  }
  this.url = url;
  this.username = username;
  this.password = password;

  this.context = HttpClientContext.create();
  if ( !StringUtil.isEmpty( hostName ) ) {
    // Preemptive Basic Authentication
    HttpHost target = new HttpHost( hostName, port, "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
    this.context.setAuthCache( authCache );
  }
  clientBuilder.setCookieSpec( CookieSpecs.DEFAULT );
  clientBuilder.setMaxRedirects( 10 );
  clientBuilder.allowCircularRedirects();
  clientBuilder.allowRelativeRedirect();
}
 
Example 7
Source File: PreemptiveBasicAuthHttpComponentsClientHttpRequestFactory.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
@Override
protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
	final AuthCache authCache = new BasicAuthCache();

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

	final BasicHttpContext localcontext = new BasicHttpContext();
	localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
	return localcontext;
}
 
Example 8
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 9
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 10
Source File: LocalFileModel.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @deprecated use {@link LocalFileModel#LocalFileModel(java.lang.String,
 * org.pentaho.reporting.engine.classic.core.util.HttpClientManager.HttpClientBuilderFacade,
 * java.lang.String, java.lang.String, java.lang.String, int) }.
 */
@Deprecated()
public LocalFileModel( final String url,
                       final HttpClient client,
                       final String username,
                       final String password,
                       final String hostName,
                       int port ) {
  if ( url == null ) {
    throw new NullPointerException();
  }
  this.url = url;
  this.username = username;
  this.password = password;
  this.client = client;

  this.context = HttpClientContext.create();
  if ( !StringUtil.isEmpty( hostName ) ) {
    // Preemptive Basic Authentication
    HttpHost target = new HttpHost( hostName, port, "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
    this.context.setAuthCache( authCache );
  }
  this.client.getParams().setParameter( ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY );
  this.client.getParams().setParameter( ClientPNames.MAX_REDIRECTS, Integer.valueOf( 10 ) );
  this.client.getParams().setParameter( ClientPNames.ALLOW_CIRCULAR_REDIRECTS, Boolean.TRUE );
  this.client.getParams().setParameter( ClientPNames.REJECT_RELATIVE_REDIRECT, Boolean.FALSE );
}
 
Example 11
Source File: FileDownloader.java    From frontend-maven-plugin with Apache License 2.0 5 votes vote down vote up
private HttpClientContext makeLocalContext(URL requestUrl) {
    // Auth target host
    HttpHost target = new HttpHost (requestUrl.getHost(), requestUrl.getPort(), requestUrl.getProtocol());
    // 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
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    return localContext;
}
 
Example 12
Source File: HttpComponentsClientHttpRequestFactoryBasicAuth.java    From spring-hmac-rest with MIT License 5 votes vote down vote up
private HttpContext createHttpContext() {
    // 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(host, basicAuth);

    // Add AuthCache to the execution context
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
    localcontext.setAttribute(HttpClientContext.CREDS_PROVIDER, credentialsProvider);

    return localcontext;
}
 
Example 13
Source File: PreemptiveBasicAuthHttpComponentsClientHttpRequestFactory.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
@Override
protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
	final AuthCache authCache = new BasicAuthCache();

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

	final BasicHttpContext localcontext = new BasicHttpContext();
	localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
	return localcontext;
}
 
Example 14
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 15
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 16
Source File: RabbitMQHttpClient.java    From kkbinlog with Apache License 2.0 5 votes vote down vote up
private HttpComponentsClientHttpRequestFactory getRequestFactory(final URL url, final String username, final String password, final SSLConnectionSocketFactory sslConnectionSocketFactory, final SSLContext sslContext) throws MalformedURLException {
    String theUser = username;
    String thePassword = password;
    String userInfo = url.getUserInfo();
    if (userInfo != null && theUser == null) {
        String[] userParts = userInfo.split(":");
        if (userParts.length > 0) {
            theUser = userParts[0];
        }
        if (userParts.length > 1) {
            thePassword = userParts[1];
        }
    }
    final HttpClientBuilder bldr = HttpClientBuilder.create().
            setDefaultCredentialsProvider(getCredentialsProvider(url, theUser, thePassword));
    bldr.setDefaultHeaders(Arrays.asList(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json")));
    if (sslConnectionSocketFactory != null) {
        bldr.setSSLSocketFactory(sslConnectionSocketFactory);
    }
    if (sslContext != null) {
        bldr.setSslcontext(sslContext);
    }

    HttpClient httpClient = bldr.build();

    // RabbitMQ HTTP API currently does not support challenge/response for PUT methods.
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicScheme = new BasicScheme();
    authCache.put(new HttpHost(rootUri.getHost(), rootUri.getPort(), rootUri.getScheme()), basicScheme);
    final HttpClientContext ctx = HttpClientContext.create();
    ctx.setAuthCache(authCache);
    return new HttpComponentsClientHttpRequestFactory(httpClient) {
        @Override
        protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
            return ctx;
        }
    };
}
 
Example 17
Source File: HTTPClient.java    From gocd-build-status-notifier with Apache License 2.0 5 votes vote down vote up
private AuthCache getAuthCache(AuthenticationType authenticationType, HttpHost target) {
    AuthCache authCache = new BasicAuthCache();
    if (authenticationType == AuthenticationType.BASIC) {
        authCache.put(target, new BasicScheme());
    } else {
        authCache.put(target, new DigestScheme());
    }
    return authCache;
}
 
Example 18
Source File: WebService.java    From hop 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;
}
 
Example 19
Source File: CloseableHttpProvider.java    From tokens with Apache License 2.0 5 votes vote down vote up
public CloseableHttpProvider(ClientCredentials clientCredentials, UserCredentials userCredentials,
        URI accessTokenUri, HttpConfig httpConfig) {

    this.userCredentials = userCredentials;
    this.accessTokenUri = accessTokenUri;

    requestConfig = RequestConfig.custom()
                                 .setSocketTimeout(httpConfig.getSocketTimeout())
                                 .setConnectTimeout(httpConfig.getConnectTimeout())
                                 .setConnectionRequestTimeout(httpConfig.getConnectionRequestTimeout())
                                 .setStaleConnectionCheckEnabled(httpConfig.isStaleConnectionCheckEnabled())
                                 .build();

    // prepare basic auth credentials
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(accessTokenUri.getHost(), accessTokenUri.getPort()),
            new UsernamePasswordCredentials(clientCredentials.getId(), clientCredentials.getSecret()));

    client = HttpClients.custom()
                        .setUserAgent(USER_AGENT.get())
                        .useSystemProperties()
                        .setDefaultCredentialsProvider(credentialsProvider)
                        .build();

    host = new HttpHost(accessTokenUri.getHost(), accessTokenUri.getPort(), accessTokenUri.getScheme());

    // enable basic auth for the request
    final AuthCache authCache = new BasicAuthCache();
    final BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);

    localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
}
 
Example 20
Source File: JenKinsBuildService.java    From ehousechina with Apache License 2.0 4 votes vote down vote up
private AuthCache getAuthCache(){
	AuthCache authCache = new BasicAuthCache();
	BasicScheme basicAuth = new BasicScheme();
	authCache.put(getHttpHost(), basicAuth);
	return authCache;
}