org.apache.http.client.protocol.HttpClientContext#setAuthCache ( )源码实例Demo

下面列出了org.apache.http.client.protocol.HttpClientContext#setAuthCache ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: geowave   文件: GeoServerIT.java
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);
}
 
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;
}
 
源代码3 项目: metron   文件: TaxiiHandler.java
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;
}
 
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);
    }
}
 
源代码5 项目: nexus-public   文件: FormatClientSupport.java
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);
}
 
源代码6 项目: frontend-maven-plugin   文件: FileDownloader.java
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;
}
 
源代码7 项目: gocd-build-status-notifier   文件: HTTPClient.java
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
            }
        }
    }
}
 
源代码8 项目: hop   文件: WebService.java
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;
}
 
源代码9 项目: knox   文件: GatewayBasicFuncTest.java
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" );
}
 
源代码10 项目: dss   文件: CommonsDataLoader.java
protected HttpContext getHttpContext(final HttpHost targetHost) {
	// 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
	HttpClientContext localContext = HttpClientContext.create();
	localContext.setAuthCache(authCache);
	return localContext;
}
 
源代码11 项目: cs-actions   文件: ContextBuilder.java
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;
}
 
源代码12 项目: restfiddle   文件: DigestAuthHandler.java
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;
   }
 
源代码13 项目: qpid-broker-j   文件: JavaBrokerAdmin.java
private HttpClientContext getHttpClientContext(final HttpHost management)
{
    final BasicAuthCache authCache = new BasicAuthCache();
    authCache.put(management, new BasicScheme());
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    return localContext;
}
 
源代码14 项目: qpid-broker-j   文件: ManageQpidJMSResources.java
private HttpClientContext getHttpClientContext(final HttpHost management)
{
    final BasicAuthCache authCache = new BasicAuthCache();
    authCache.put(management, new BasicScheme());
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    return localContext;
}
 
源代码15 项目: nexus-public   文件: NexusClientFactory.java
@Nullable
public T createClient(final URL repositoryUrl,
                      final String username,
                      final String password)
{
  checkNotNull(repositoryUrl);
  checkNotNull(username);
  checkNotNull(password);

  AuthScope scope = new AuthScope(repositoryUrl.getHost(), -1);
  CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(scope, new UsernamePasswordCredentials(username, password));

  RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
  requestConfigBuilder.setExpectContinueEnabled(true);

  AuthCache authCache = new BasicAuthCache();
  authCache.put(new HttpHost(repositoryUrl.getHost(), repositoryUrl.getPort()), new BasicScheme());

  HttpClientContext httpClientContext = HttpClientContext.create();
  httpClientContext.setAuthCache(authCache);
  httpClientContext.setRequestConfig(requestConfigBuilder.build());

  try {
    return createClient(
        HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build(),
        httpClientContext,
        repositoryUrl.toURI()
    );
  }
  catch (URISyntaxException e) {
    log.warn("Uri exception creating Client", e);
  }

  return null;
}
 
源代码16 项目: knox   文件: GatewayBasicFuncTest.java
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" );
  }
 
源代码17 项目: ehousechina   文件: JenKinsBuildService.java
private HttpClientContext getHttpClientContext(){
	HttpClientContext httpClientContext = HttpClientContext.create();
	httpClientContext.setCredentialsProvider(this.getCredentialsProvider());
	httpClientContext.setAuthCache(this.getAuthCache());
	return httpClientContext;
}
 
@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")));
}
 
源代码19 项目: commons-vfs   文件: Http4FileProvider.java
/**
 * 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;
}
 
源代码20 项目: nexus-public   文件: NexusITSupport.java
/**
 * @return Context with preemptive auth enabled for Nexus
 */
protected HttpClientContext clientContext() {
  HttpClientContext context = HttpClientContext.create();
  context.setAuthCache(basicAuthCache());
  return context;
}