org.apache.http.config.Lookup Java Examples

The following examples show how to use org.apache.http.config.Lookup. 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: HttpConnectionManager.java    From timer with Apache License 2.0 6 votes vote down vote up
/**
 * 默认是 Bsic认证机制
 *
 * @param ip
 * @param username
 * @param password
 * @return
 */
public static HttpClient getHtpClient(String ip, int port, String username, String password) {
    HttpHost proxy = new HttpHost(ip, port);
    Lookup<AuthSchemeProvider> authProviders =
            RegistryBuilder.<AuthSchemeProvider>create()
                    .register(AuthSchemes.BASIC, new BasicSchemeFactory())
                    .build();
    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    if (username != null && password != null) {
        credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    } else {
        credsProvider.setCredentials(AuthScope.ANY, null);
    }

    RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
    CloseableHttpClient httpClient = HttpClients
            .custom()
            .setConnectionManager(cm)
            .setProxy(proxy)
            .setRedirectStrategy(new LaxRedirectStrategy())
            .setDefaultRequestConfig(requestConfig)
            .setDefaultAuthSchemeRegistry(authProviders)
            .setDefaultCredentialsProvider(credsProvider)
            .build();
    return httpClient;
}
 
Example #2
Source File: TestInfoServersACL.java    From hbase with Apache License 2.0 6 votes vote down vote up
private CloseableHttpClient createHttpClient(String clientPrincipal) throws Exception {
  // Logs in with Kerberos via GSS
  GSSManager gssManager = GSSManager.getInstance();
  // jGSS Kerberos login constant
  Oid oid = new Oid("1.2.840.113554.1.2.2");
  GSSName gssClient = gssManager.createName(clientPrincipal, GSSName.NT_USER_NAME);
  GSSCredential credential = gssManager.createCredential(
      gssClient, GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);

  Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create()
      .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build();

  BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));

  return HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry)
      .setDefaultCredentialsProvider(credentialsProvider).build();
}
 
Example #3
Source File: YarnClient.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private static HttpClient buildSpengoHttpClient() {
  HttpClientBuilder builder = HttpClientBuilder.create();
  Lookup<AuthSchemeProvider> authSchemeRegistry
      = RegistryBuilder.<AuthSchemeProvider>create().register(
          AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();
  builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
  BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(new AuthScope(null, -1, null), new Credentials() {
    @Override
    public Principal getUserPrincipal() {
      return null;
    }

    @Override
    public String getPassword() {
      return null;
    }
  });
  builder.setDefaultCredentialsProvider(credentialsProvider);

  // Avoid output WARN: Cookie rejected
  RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES)
      .build();
  builder.setDefaultRequestConfig(globalConfig);

  CloseableHttpClient httpClient = builder.build();

  return httpClient;
}
 
Example #4
Source File: LivySessionController.java    From nifi with Apache License 2.0 5 votes vote down vote up
private HttpClient openConnection() throws IOException {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    if (sslContextService != null) {
        try {
            SSLContext sslContext = getSslSocketFactory(sslContextService);
            httpClientBuilder.setSSLContext(sslContext);
        } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | UnrecoverableKeyException | KeyManagementException e) {
            throw new IOException(e);
        }
    }

    if (credentialsService != null) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(null, -1, null),
            new KerberosKeytabCredentials(credentialsService.getPrincipal(), credentialsService.getKeytab()));
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create()
            .register(AuthSchemes.SPNEGO, new KerberosKeytabSPNegoAuthSchemeProvider()).build();
        httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
    }

    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectTimeout(connectTimeout);
    requestConfigBuilder.setConnectionRequestTimeout(connectTimeout);
    requestConfigBuilder.setSocketTimeout(connectTimeout);
    httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());

    return httpClientBuilder.build();
}
 
Example #5
Source File: KerberosHttpClientBuilder.java    From nifi with Apache License 2.0 5 votes vote down vote up
public SolrHttpClientBuilder getBuilder(SolrHttpClientBuilder builder) {

        //Enable only SPNEGO authentication scheme.

        builder.setAuthSchemeRegistryProvider(() -> {
            Lookup<AuthSchemeProvider> authProviders = RegistryBuilder.<AuthSchemeProvider>create()
                    .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, false))
                    .build();
            return authProviders;
        });
        // Get the credentials from the JAAS configuration rather than here
        Credentials useJaasCreds = new Credentials() {
            public String getPassword() {
                return null;
            }
            public Principal getUserPrincipal() {
                return null;
            }
        };

        HttpClientUtil.setCookiePolicy(SolrPortAwareCookieSpecFactory.POLICY_NAME);

        builder.setCookieSpecRegistryProvider(() -> {
            SolrPortAwareCookieSpecFactory cookieFactory = new SolrPortAwareCookieSpecFactory();

            Lookup<CookieSpecProvider> cookieRegistry = RegistryBuilder.<CookieSpecProvider> create()
                    .register(SolrPortAwareCookieSpecFactory.POLICY_NAME, cookieFactory).build();

            return cookieRegistry;
        });

        builder.setDefaultCredentialsProvider(() -> {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, useJaasCreds);
            return credentialsProvider;
        });
        HttpClientUtil.addRequestInterceptor(bufferedEntityInterceptor);
        return builder;
    }
 
Example #6
Source File: AuthSchemeProviderLookupBuilderTest.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
private AuthSchemeProvider getAuthSchemeProvider(String authType) {
    AuthTypes authTypes = new AuthTypes(authType);
    Lookup<AuthSchemeProvider> lookup = new AuthSchemeProviderLookupBuilder()
            .setHeaders(new ArrayList<Header>())
            .setAuthTypes(authTypes)
            .buildAuthSchemeProviderLookup();
    return lookup.lookup(authType);
}
 
Example #7
Source File: DefaultApacheHttpClientConnectionManagerFactoryTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
private X509TrustManager getX509TrustManager(
		Lookup<ConnectionSocketFactory> socketFactoryRegistry) {
	ConnectionSocketFactory connectionSocketFactory = socketFactoryRegistry
			.lookup("https");
	SSLSocketFactory sslSocketFactory = getField(connectionSocketFactory,
			"socketfactory");
	SSLContextSpi sslContext = getField(sslSocketFactory, "context");
	return getField(sslContext, "trustManager");
}
 
Example #8
Source File: DefaultApacheHttpClientConnectionManagerFactoryTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void newConnectionManagerWithDisabledSSLValidation() throws Exception {
	HttpClientConnectionManager connectionManager = new DefaultApacheHttpClientConnectionManagerFactory()
			.newConnectionManager(true, 2, 6);

	Lookup<ConnectionSocketFactory> socketFactoryRegistry = getConnectionSocketFactoryLookup(
			connectionManager);
	then(socketFactoryRegistry.lookup("https")).isNotNull();
	then(getX509TrustManager(socketFactoryRegistry).getAcceptedIssuers()).isNull();
}
 
Example #9
Source File: DefaultApacheHttpClientConnectionManagerFactoryTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void newConnectionManagerWithSSL() throws Exception {
	HttpClientConnectionManager connectionManager = new DefaultApacheHttpClientConnectionManagerFactory()
			.newConnectionManager(false, 2, 6);

	Lookup<ConnectionSocketFactory> socketFactoryRegistry = getConnectionSocketFactoryLookup(
			connectionManager);
	then(socketFactoryRegistry.lookup("https")).isNotNull();
	then(getX509TrustManager(socketFactoryRegistry).getAcceptedIssuers()).isNotNull();
}
 
Example #10
Source File: ExtendedConnectionOperator.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Lookup<ConnectionSocketFactory> getSocketFactoryRegistry(HttpContext context) {
  Lookup<ConnectionSocketFactory> registry = (Lookup<ConnectionSocketFactory>)
      context.getAttribute(SOCKET_FACTORY_REGISTRY);

  if (registry == null) {
    registry = this.socketFactoryRegistry;
  }

  return registry;
}
 
Example #11
Source File: ExtendedConnectionOperator.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private ConnectionSocketFactory getSocketFactory(HttpHost host, HttpContext context) throws IOException {
  Lookup<ConnectionSocketFactory> registry = getSocketFactoryRegistry(context);
  ConnectionSocketFactory socketFactory = registry.lookup(host.getSchemeName());

  if (socketFactory == null) {
    throw new UnsupportedSchemeException(host.getSchemeName() + " protocol is not supported");
  }

  return socketFactory;
}
 
Example #12
Source File: FeignHttpClientConfigurationTests.java    From spring-cloud-openfeign with Apache License 2.0 5 votes vote down vote up
@Test
public void disableSslTest() throws Exception {
	HttpClientConnectionManager connectionManager = this.context
			.getBean(HttpClientConnectionManager.class);
	Lookup<ConnectionSocketFactory> socketFactoryRegistry = getConnectionSocketFactoryLookup(
			connectionManager);
	assertThat(socketFactoryRegistry.lookup("https")).isNotNull();
	assertThat(this.getX509TrustManager(socketFactoryRegistry).getAcceptedIssuers())
			.isNull();
}
 
Example #13
Source File: FeignHttpClientConfigurationTests.java    From spring-cloud-openfeign with Apache License 2.0 5 votes vote down vote up
private X509TrustManager getX509TrustManager(
		Lookup<ConnectionSocketFactory> socketFactoryRegistry) {
	ConnectionSocketFactory connectionSocketFactory = (ConnectionSocketFactory) socketFactoryRegistry
			.lookup("https");
	SSLSocketFactory sslSocketFactory = (SSLSocketFactory) this
			.getField(connectionSocketFactory, "socketfactory");
	SSLContextSpi sslContext = (SSLContextSpi) this.getField(sslSocketFactory,
			"context");
	return (X509TrustManager) this.getField(sslContext, "trustManager");
}
 
Example #14
Source File: ExtendedConnectionOperator.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
public ExtendedConnectionOperator(
    Lookup<ConnectionSocketFactory> socketFactoryRegistry,
    SchemePortResolver schemePortResolver,
    DnsResolver dnsResolver
) {
  this.socketFactoryRegistry = socketFactoryRegistry;
  this.schemePortResolver = schemePortResolver != null ? schemePortResolver : DefaultSchemePortResolver.INSTANCE;
  this.dnsResolver = dnsResolver != null ? dnsResolver : SystemDefaultDnsResolver.INSTANCE;
}
 
Example #15
Source File: TestThriftSpnegoHttpFallbackServer.java    From hbase with Apache License 2.0 4 votes vote down vote up
private CloseableHttpClient createHttpClient() throws Exception {
  final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(clientPrincipal, clientKeytab);
  final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
  // Make sure the subject has a principal
  assertFalse("Found no client principals in the clientSubject.",
    clientPrincipals.isEmpty());

  // Get a TGT for the subject (might have many, different encryption types). The first should
  // be the default encryption type.
  Set<KerberosTicket> privateCredentials =
    clientSubject.getPrivateCredentials(KerberosTicket.class);
  assertFalse("Found no private credentials in the clientSubject.",
    privateCredentials.isEmpty());
  KerberosTicket tgt = privateCredentials.iterator().next();
  assertNotNull("No kerberos ticket found.", tgt);

  // The name of the principal
  final String clientPrincipalName = clientPrincipals.iterator().next().getName();

  return Subject.doAs(clientSubject, (PrivilegedExceptionAction<CloseableHttpClient>) () -> {
    // Logs in with Kerberos via GSS
    GSSManager gssManager = GSSManager.getInstance();
    // jGSS Kerberos login constant
    Oid oid = new Oid("1.2.840.113554.1.2.2");
    GSSName gssClient = gssManager.createName(clientPrincipalName, GSSName.NT_USER_NAME);
    GSSCredential credential = gssManager.createCredential(gssClient,
      GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);

    Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create()
      .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true))
      .build();

    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));

    return HttpClients.custom()
      .setDefaultAuthSchemeRegistry(authRegistry)
      .setDefaultCredentialsProvider(credentialsProvider)
      .build();
  });
}
 
Example #16
Source File: FeignHttpClientConfigurationTests.java    From spring-cloud-openfeign with Apache License 2.0 4 votes vote down vote up
private Lookup<ConnectionSocketFactory> getConnectionSocketFactoryLookup(
		HttpClientConnectionManager connectionManager) {
	DefaultHttpClientConnectionOperator connectionOperator = (DefaultHttpClientConnectionOperator) this
			.getField(connectionManager, "connectionOperator");
	return (Lookup) this.getField(connectionOperator, "socketFactoryRegistry");
}
 
Example #17
Source File: ContextBuilder.java    From cs-actions with Apache License 2.0 4 votes vote down vote up
public ContextBuilder setAuthSchemeLookup(Lookup<AuthSchemeProvider> authSchemeLookup) {
    this.authSchemeLookup = authSchemeLookup;
    return this;
}
 
Example #18
Source File: TestProxyUserSpnegoHttpServer.java    From hbase with Apache License 2.0 4 votes vote down vote up
public void testProxy(String clientPrincipal, String doAs, int responseCode, String statusLine) throws Exception {
  // Create the subject for the client
  final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(WHEEL_PRINCIPAL, wheelKeytab);
  final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
  // Make sure the subject has a principal
  assertFalse(clientPrincipals.isEmpty());

  // Get a TGT for the subject (might have many, different encryption types). The first should
  // be the default encryption type.
  Set<KerberosTicket> privateCredentials =
          clientSubject.getPrivateCredentials(KerberosTicket.class);
  assertFalse(privateCredentials.isEmpty());
  KerberosTicket tgt = privateCredentials.iterator().next();
  assertNotNull(tgt);

  // The name of the principal
  final String principalName = clientPrincipals.iterator().next().getName();

  // Run this code, logged in as the subject (the client)
  HttpResponse resp = Subject.doAs(clientSubject, new PrivilegedExceptionAction<HttpResponse>() {
      @Override
      public HttpResponse run() throws Exception {
        // Logs in with Kerberos via GSS
        GSSManager gssManager = GSSManager.getInstance();
        // jGSS Kerberos login constant
        Oid oid = new Oid("1.2.840.113554.1.2.2");
        GSSName gssClient = gssManager.createName(principalName, GSSName.NT_USER_NAME);
        GSSCredential credential = gssManager.createCredential(gssClient,
            GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);

        HttpClientContext context = HttpClientContext.create();
        Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true))
            .build();

        HttpClient client = HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry)
                .build();
        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));

        URL url = new URL(getServerURL(server), "/echo?doAs=" + doAs + "&a=b");
        context.setTargetHost(new HttpHost(url.getHost(), url.getPort()));
        context.setCredentialsProvider(credentialsProvider);
        context.setAuthSchemeRegistry(authRegistry);

        HttpGet get = new HttpGet(url.toURI());
        return client.execute(get, context);
      }
  });

  assertNotNull(resp);
  assertEquals(responseCode, resp.getStatusLine().getStatusCode());
  if(responseCode == HttpURLConnection.HTTP_OK) {
      assertTrue(EntityUtils.toString(resp.getEntity()).trim().contains("a:b"));
  } else {
      assertTrue(resp.getStatusLine().toString().contains(statusLine));
  }
}
 
Example #19
Source File: TestSpnegoHttpServer.java    From hbase with Apache License 2.0 4 votes vote down vote up
@Test
public void testAllowedClient() throws Exception {
  // Create the subject for the client
  final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(CLIENT_PRINCIPAL, clientKeytab);
  final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
  // Make sure the subject has a principal
  assertFalse(clientPrincipals.isEmpty());

  // Get a TGT for the subject (might have many, different encryption types). The first should
  // be the default encryption type.
  Set<KerberosTicket> privateCredentials =
          clientSubject.getPrivateCredentials(KerberosTicket.class);
  assertFalse(privateCredentials.isEmpty());
  KerberosTicket tgt = privateCredentials.iterator().next();
  assertNotNull(tgt);

  // The name of the principal
  final String principalName = clientPrincipals.iterator().next().getName();

  // Run this code, logged in as the subject (the client)
  HttpResponse resp = Subject.doAs(clientSubject, new PrivilegedExceptionAction<HttpResponse>() {
      @Override
      public HttpResponse run() throws Exception {
        // Logs in with Kerberos via GSS
        GSSManager gssManager = GSSManager.getInstance();
        // jGSS Kerberos login constant
        Oid oid = new Oid("1.2.840.113554.1.2.2");
        GSSName gssClient = gssManager.createName(principalName, GSSName.NT_USER_NAME);
        GSSCredential credential = gssManager.createCredential(gssClient,
            GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);

        HttpClientContext context = HttpClientContext.create();
        Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true))
            .build();

        HttpClient client = HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry)
                .build();
        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));

        URL url = new URL(getServerURL(server), "/echo?a=b");
        context.setTargetHost(new HttpHost(url.getHost(), url.getPort()));
        context.setCredentialsProvider(credentialsProvider);
        context.setAuthSchemeRegistry(authRegistry);

        HttpGet get = new HttpGet(url.toURI());
        return client.execute(get, context);
      }
  });

  assertNotNull(resp);
  assertEquals(HttpURLConnection.HTTP_OK, resp.getStatusLine().getStatusCode());
  assertEquals("a:b", EntityUtils.toString(resp.getEntity()).trim());
}
 
Example #20
Source File: Krb5HttpClientBuilder.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public SolrHttpClientBuilder getBuilder(SolrHttpClientBuilder builder) {
  if (System.getProperty(LOGIN_CONFIG_PROP) != null) {
    String configValue = System.getProperty(LOGIN_CONFIG_PROP);

    if (configValue != null) {
      log.info("Setting up SPNego auth with config: {}", configValue);
      final String useSubjectCredsProp = "javax.security.auth.useSubjectCredsOnly";
      String useSubjectCredsVal = System.getProperty(useSubjectCredsProp);

      // "javax.security.auth.useSubjectCredsOnly" should be false so that the underlying
      // authentication mechanism can load the credentials from the JAAS configuration.
      if (useSubjectCredsVal == null) {
        System.setProperty(useSubjectCredsProp, "false");
      } else if (!useSubjectCredsVal.toLowerCase(Locale.ROOT).equals("false")) {
        // Don't overwrite the prop value if it's already been written to something else,
        // but log because it is likely the Credentials won't be loaded correctly.
        log.warn("System Property: {} set to: {} not false.  SPNego authentication may not be successful."
            , useSubjectCredsProp, useSubjectCredsVal);
      }

      javax.security.auth.login.Configuration.setConfiguration(jaasConfig);
      //Enable only SPNEGO authentication scheme.

      builder.setAuthSchemeRegistryProvider(() -> {
        Lookup<AuthSchemeProvider> authProviders = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, false))
            .build();
        return authProviders;
      });
      // Get the credentials from the JAAS configuration rather than here
      Credentials useJaasCreds = new Credentials() {
        public String getPassword() {
          return null;
        }
        public Principal getUserPrincipal() {
          return null;
        }
      };

      HttpClientUtil.setCookiePolicy(SolrPortAwareCookieSpecFactory.POLICY_NAME);

      builder.setCookieSpecRegistryProvider(() -> {
        SolrPortAwareCookieSpecFactory cookieFactory = new SolrPortAwareCookieSpecFactory();

        Lookup<CookieSpecProvider> cookieRegistry = RegistryBuilder.<CookieSpecProvider> create()
            .register(SolrPortAwareCookieSpecFactory.POLICY_NAME, cookieFactory).build();

        return cookieRegistry;
      });
      
      builder.setDefaultCredentialsProvider(() -> {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, useJaasCreds);
        return credentialsProvider;
      });
      HttpClientUtil.addRequestInterceptor(bufferedEntityInterceptor);
    }
  } else {
    log.warn("{} is configured without specifying system property '{}'",
        getClass().getName(), LOGIN_CONFIG_PROP);
  }

  return builder;
}
 
Example #21
Source File: TestThriftSpnegoHttpServer.java    From hbase with Apache License 2.0 4 votes vote down vote up
private CloseableHttpClient createHttpClient() throws Exception {
  final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(clientPrincipal, clientKeytab);
  final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
  // Make sure the subject has a principal
  assertFalse("Found no client principals in the clientSubject.",
    clientPrincipals.isEmpty());

  // Get a TGT for the subject (might have many, different encryption types). The first should
  // be the default encryption type.
  Set<KerberosTicket> privateCredentials =
      clientSubject.getPrivateCredentials(KerberosTicket.class);
  assertFalse("Found no private credentials in the clientSubject.",
    privateCredentials.isEmpty());
  KerberosTicket tgt = privateCredentials.iterator().next();
  assertNotNull("No kerberos ticket found.", tgt);

  // The name of the principal
  final String clientPrincipalName = clientPrincipals.iterator().next().getName();

  return Subject.doAs(clientSubject, (PrivilegedExceptionAction<CloseableHttpClient>) () -> {
    // Logs in with Kerberos via GSS
    GSSManager gssManager = GSSManager.getInstance();
    // jGSS Kerberos login constant
    Oid oid = new Oid("1.2.840.113554.1.2.2");
    GSSName gssClient = gssManager.createName(clientPrincipalName, GSSName.NT_USER_NAME);
    GSSCredential credential = gssManager.createCredential(gssClient,
        GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);

    Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create()
        .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true))
        .build();

    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));

    return HttpClients.custom()
        .setDefaultAuthSchemeRegistry(authRegistry)
        .setDefaultCredentialsProvider(credentialsProvider)
        .build();
  });
}
 
Example #22
Source File: DefaultApacheHttpClientConnectionManagerFactoryTests.java    From spring-cloud-commons with Apache License 2.0 4 votes vote down vote up
private Lookup<ConnectionSocketFactory> getConnectionSocketFactoryLookup(
		HttpClientConnectionManager connectionManager) {
	DefaultHttpClientConnectionOperator connectionOperator = getField(
			connectionManager, "connectionOperator");
	return getField(connectionOperator, "socketFactoryRegistry");
}
 
Example #23
Source File: HttpClientHandler.java    From ant-ivy with Apache License 2.0 4 votes vote down vote up
private static Lookup<AuthSchemeProvider> createAuthSchemeRegistry() {
    return RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.DIGEST, new DigestSchemeFactory())
            .register(AuthSchemes.BASIC, new BasicSchemeFactory())
            .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
            .build();
}
 
Example #24
Source File: HttpClientUtils.java    From turbo-rpc with Apache License 2.0 4 votes vote down vote up
public static CloseableHttpClient createHttpClient(int concurrency) {
	HttpClientBuilder builder = HttpClientBuilder.create();

	PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
	connManager.setDefaultMaxPerRoute(concurrency);
	connManager.setMaxTotal(concurrency);

	RequestConfig requestConfig = RequestConfig.custom()//
			.setAuthenticationEnabled(true)//
			.setSocketTimeout(SOCKET_TIMEOUT)//
			.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)//
			.setConnectTimeout(CONNECT_TIMEOUT)//
			.setRedirectsEnabled(true)//
			.setRelativeRedirectsAllowed(true)//
			.setMaxRedirects(15)//
			.build();

	SocketConfig socketConfig = SocketConfig.custom()//
			.setSoKeepAlive(true)//
			.setSoReuseAddress(true)//
			.build();

	CookieSpecProvider cookieSpecProvider = new IgnoreSpecProvider();
	Lookup<CookieSpecProvider> cookieSpecRegistry = RegistryBuilder.<CookieSpecProvider>create()//
			.register(CookieSpecs.DEFAULT, cookieSpecProvider)//
			.register(CookieSpecs.STANDARD, cookieSpecProvider)//
			.register(CookieSpecs.STANDARD_STRICT, cookieSpecProvider)//
			.build();

	builder.setConnectionManager(connManager);
	builder.setDefaultSocketConfig(socketConfig);
	builder.setDefaultRequestConfig(requestConfig);
	builder.setDefaultCookieSpecRegistry(cookieSpecRegistry);

	return builder.addInterceptorLast((HttpRequest request, HttpContext context) -> {
		request.removeHeaders("Host");
		request.removeHeaders("Accept-Encoding");
		//request.removeHeaders("Connection");
		request.removeHeaders("User-Agent");
	}).build();
}
 
Example #25
Source File: CoreContainer.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public Lookup<AuthSchemeProvider> getAuthSchemeRegistry() {
  return builder.getAuthSchemeRegistryProvider().getAuthSchemeRegistry();
}
 
Example #26
Source File: SolrHttpClientBuilder.java    From lucene-solr with Apache License 2.0 votes vote down vote up
Lookup<AuthSchemeProvider> getAuthSchemeRegistry(); 
Example #27
Source File: SolrHttpClientBuilder.java    From lucene-solr with Apache License 2.0 votes vote down vote up
Lookup<CookieSpecProvider> getCookieSpecRegistry(); 
Example #28
Source File: SolrHttpClientContextBuilder.java    From lucene-solr with Apache License 2.0 votes vote down vote up
public abstract Lookup<AuthSchemeProvider> getAuthSchemeRegistry(); 
Example #29
Source File: SolrHttpClientContextBuilder.java    From lucene-solr with Apache License 2.0 votes vote down vote up
public abstract Lookup<CookieSpecProvider> getCookieSpecRegistry();