类org.apache.http.client.AuthCache源码实例Demo

下面列出了怎么用org.apache.http.client.AuthCache的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: hop   文件: HopServer.java
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 );
  }
 
源代码2 项目: hop   文件: HttpClientUtil.java
/**
 * 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;
}
 
源代码3 项目: quarkus   文件: Substitute_RestClient.java
@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();
}
 
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;
}
 
源代码5 项目: nextcloud-java-api   文件: ConnectorCommon.java
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;
}
 
源代码6 项目: aws-sdk-java-v2   文件: ApacheUtils.java
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);
    }
}
 
源代码7 项目: ibm-cos-sdk-java   文件: ApacheUtils.java
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);
    }
}
 
源代码8 项目: rdf4j   文件: SPARQLProtocolSession.java
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);
		}
	}
 
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);
    }
}
 
源代码10 项目: etherjar   文件: HttpRpcTransport.java
/**
 * 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;
}
 
源代码11 项目: 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);
}
 
源代码12 项目: 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);
}
 
源代码13 项目: 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;
}
 
源代码14 项目: hbase   文件: TestSecureRESTServer.java
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);
}
 
源代码15 项目: reef   文件: HDInsightInstance.java
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;
}
 
源代码16 项目: 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);
}
 
源代码17 项目: pentaho-reporting   文件: HttpClientUtil.java
/**
 * 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;
}
 
/**
 * 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;
}
 
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;
}
 
源代码20 项目: pentaho-kettle   文件: HttpClientUtil.java
/**
 * 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;
}
 
源代码21 项目: hop   文件: HopServerTest.java
@Test
public void testAuthCredentialsSchemeWithSSL() {
  hopServer.setUsername( "admin" );
  hopServer.setPassword( "password" );
  hopServer.setHostname( "localhost" );
  hopServer.setPort( "8443" );
  hopServer.setSslMode( true );

  AuthCache cache = hopServer.getAuthContext().getAuthCache();
  assertNotNull( cache.get( new HttpHost( "localhost", 8443, "https" ) ) );
  assertNull( cache.get( new HttpHost( "localhost", 8443, "http" ) ) );
}
 
源代码22 项目: hop   文件: HopServerTest.java
@Test
public void testAuthCredentialsSchemeWithoutSSL() {
  hopServer.setUsername( "admin" );
  hopServer.setPassword( "password" );
  hopServer.setHostname( "localhost" );
  hopServer.setPort( "8080" );
  hopServer.setSslMode( false );

  AuthCache cache = hopServer.getAuthContext().getAuthCache();
  assertNull( cache.get( new HttpHost( "localhost", 8080, "https" ) ) );
  assertNotNull( cache.get( new HttpHost( "localhost", 8080, "http" ) ) );
}
 
源代码23 项目: 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;
}
 
源代码24 项目: service-now-plugin   文件: ServiceNowExecution.java
private CloseableHttpClient authenticate(HttpClientBuilder clientBuilder, HttpRequestBase requestBase, HttpContext httpContext) {
    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(
            new AuthScope(requestBase.getURI().getHost(), requestBase.getURI().getPort()),
            CredentialsUtil.readCredentials(credentials, vaultConfiguration));
    clientBuilder.setDefaultCredentialsProvider(provider);

    AuthCache authCache = new BasicAuthCache();
    authCache.put(URIUtils.extractHost(requestBase.getURI()), new BasicScheme());
    httpContext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);

    return clientBuilder.build();
}
 
源代码25 项目: kkbinlog   文件: RabbitMQHttpClient.java
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;
        }
    };
}
 
@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;
}
 
源代码27 项目: ats-framework   文件: HttpClient.java
/**
 * Set up authentication for HTTP Basic/HTTP Digest/SPNEGO.
 *
 * @param httpClientBuilder The client builder
 * @return The context
 * @throws HttpException
 */
private void setupAuthentication( HttpClientBuilder httpClientBuilder ) throws HttpException {

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                                 new UsernamePasswordCredentials(username, password));
    httpClientBuilder.setDefaultCredentialsProvider(credsProvider);

    if (authType == AuthType.always) {
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();

        HttpHost target = new HttpHost(host, port, isOverSsl
                                                             ? "https"
                                                             : "http");
        authCache.put(target, basicAuth);

        // Add AuthCache to the execution context
        httpContext.setAuthCache(authCache);
    } else {
        if (!StringUtils.isNullOrEmpty(kerberosServicePrincipalName)) {
            GssClient gssClient = new GssClient(username, password, kerberosClientKeytab, krb5ConfFile);
            AuthSchemeProvider nsf = new SPNegoSchemeFactory(gssClient, kerberosServicePrincipalName,
                                                             kerberosServicePrincipalType);
            final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create()
                                                                                   .register(AuthSchemes.SPNEGO,
                                                                                             nsf)
                                                                                   .build();
            httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
        }
    }
}
 
public final HttpContext createContext(URI uri,
        UsernamePasswordCredentials creds) throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
            new AuthScope(uri.getHost(), uri.getPort()),
            creds);
    org.apache.http.HttpHost host = new org.apache.http.HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);
    HttpClientContext context1 = HttpClientContext.create();
    context1.setCredentialsProvider(credsProvider);
    context1.setAuthCache(authCache);
    return context1;
}
 
@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;
}
 
源代码30 项目: 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;
}
 
 类所在包
 类方法
 同包方法