org.apache.http.auth.AuthSchemeProvider Java Examples

The following examples show how to use org.apache.http.auth.AuthSchemeProvider. 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: TestSecureRESTServer.java    From hbase with Apache License 2.0 6 votes vote down vote up
private Pair<CloseableHttpClient,HttpClientContext> getClient() {
  HttpClientConnectionManager pool = new PoolingHttpClientConnectionManager();
  HttpHost host = new HttpHost("localhost", REST_TEST.getServletPort());
  Registry<AuthSchemeProvider> authRegistry =
      RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO,
          new SPNegoSchemeFactory(true, true)).build();
  CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(AuthScope.ANY, EmptyCredentials.INSTANCE);
  AuthCache authCache = new BasicAuthCache();

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

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

  return new Pair<>(client, context);
}
 
Example #2
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 #3
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 #4
Source File: AvaticaCommonsHttpClientImpl.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Override public void setUsernamePassword(AuthenticationType authType, String username,
    String password) {
  this.credentials = new UsernamePasswordCredentials(
      Objects.requireNonNull(username), Objects.requireNonNull(password));

  this.credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(AuthScope.ANY, credentials);

  RegistryBuilder<AuthSchemeProvider> authRegistryBuilder = RegistryBuilder.create();
  switch (authType) {
  case BASIC:
    authRegistryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory());
    break;
  case DIGEST:
    authRegistryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory());
    break;
  default:
    throw new IllegalArgumentException("Unsupported authentiation type: " + authType);
  }
  this.authRegistry = authRegistryBuilder.build();
}
 
Example #5
Source File: AbstractUnitTest.java    From elasticsearch-shield-kerberos-realm with Apache License 2.0 6 votes vote down vote up
protected final CloseableHttpClient getHttpClient(final boolean useSpnego) throws Exception {

        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        final HttpClientBuilder hcb = HttpClients.custom();

        if (useSpnego) {
            //SPNEGO/Kerberos setup
            log.debug("SPNEGO activated");
            final AuthSchemeProvider nsf = new SPNegoSchemeFactory(true);//  new NegotiateSchemeProvider();
            final Credentials jaasCreds = new JaasCredentials();
            credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.SPNEGO), jaasCreds);
            credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM), new NTCredentials("Guest", "Guest", "Guest",
                    "Guest"));
            final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create()
                    .register(AuthSchemes.SPNEGO, nsf).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build();

            hcb.setDefaultAuthSchemeRegistry(authSchemeRegistry);
        }

        hcb.setDefaultCredentialsProvider(credsProvider);
        hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(10 * 1000).build());
        final CloseableHttpClient httpClient = hcb.build();
        return httpClient;
    }
 
Example #6
Source File: AuthSchemeProviderLookupBuilderTest.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
@Test
public void buildLookupWithKerberosAuth() {
    AuthTypes authTypes = new AuthTypes(AuthSchemes.KERBEROS);
    AuthSchemeProvider provider = new AuthSchemeProviderLookupBuilder()
            .setAuthTypes(authTypes)
            .setHost("myweb.contoso.com").buildAuthSchemeProviderLookup().lookup(AuthSchemes.KERBEROS);
    assertThat(provider, instanceOf(KerberosSchemeFactory.class));
}
 
Example #7
Source File: BaseZookeeperURLManager.java    From knox with Apache License 2.0 5 votes vote down vote up
/**
 * Construct an Apache HttpClient with suitable timeout and authentication.
 *
 * @return Apache HttpClient
 */
private CloseableHttpClient buildHttpClient() {
  CloseableHttpClient client;

  // Construct a HttpClient with short term timeout
  RequestConfig.Builder requestBuilder = RequestConfig.custom()
                                                      .setConnectTimeout(TIMEOUT)
                                                      .setSocketTimeout(TIMEOUT)
                                                      .setConnectionRequestTimeout(TIMEOUT);

  // If Kerberos is enabled, allow for challenge/response transparent to client
  if (Boolean.getBoolean(GatewayConfig.HADOOP_KERBEROS_SECURED)) {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new NullCredentials());

    Registry<AuthSchemeProvider> authSchemeRegistry =
                          RegistryBuilder.<AuthSchemeProvider>create()
                                         .register(AuthSchemes.SPNEGO, new KnoxSpnegoAuthSchemeFactory(true))
                                         .build();

    client = HttpClientBuilder.create()
                              .setDefaultRequestConfig(requestBuilder.build())
                              .setDefaultAuthSchemeRegistry(authSchemeRegistry)
                              .setDefaultCredentialsProvider(credentialsProvider)
                              .build();
  } else {
    client = HttpClientBuilder.create()
                              .setDefaultRequestConfig(requestBuilder.build())
                              .build();
  }

  return client;
}
 
Example #8
Source File: WebServicesClient.java    From Bats with Apache License 2.0 5 votes vote down vote up
private static void setupUserPassAuthScheme(AuthScheme scheme, String httpScheme, AuthSchemeProvider provider, ConfigProvider configuration)
{
  String username = configuration.getProperty(scheme, "username");
  String password = configuration.getProperty(scheme, "password");
  if ((username != null) && (password != null)) {
    LOG.info("Setting up scheme {}", scheme);
    AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, httpScheme);
    Credentials credentials = new UsernamePasswordCredentials(username, password);
    setupHttpAuthScheme(httpScheme, provider, authScope, credentials);
  } else if ((username != null) || (password != null)) {
    LOG.warn("Not setting up scheme {}, missing credentials {}", scheme, (username == null) ? "username" : "password");
  }
}
 
Example #9
Source File: AuthSchemeProviderLookupBuilderTest.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
@Test
public void buildLookupWithBasicAuth() {
    AuthSchemeProvider provider = getAuthSchemeProvider(AuthSchemes.BASIC);
    assertThat(provider, instanceOf(BasicSchemeFactory.class));
    BasicScheme basicSchema = ((BasicScheme) provider.create(null));
    assertEquals("UTF-8", basicSchema.getCredentialsCharset().toString());
}
 
Example #10
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 #11
Source File: WebServicesClient.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
private static void setupUserPassAuthScheme(AuthScheme scheme, String httpScheme, AuthSchemeProvider provider, ConfigProvider configuration)
{
  String username = configuration.getProperty(scheme, "username");
  String password = configuration.getProperty(scheme, "password");
  if ((username != null) && (password != null)) {
    LOG.info("Setting up scheme {}", scheme);
    AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, httpScheme);
    Credentials credentials = new UsernamePasswordCredentials(username, password);
    setupHttpAuthScheme(httpScheme, provider, authScope, credentials);
  } else if ((username != null) || (password != null)) {
    LOG.warn("Not setting up scheme {}, missing credentials {}", scheme, (username == null) ? "username" : "password");
  }
}
 
Example #12
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 #13
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 #14
Source File: AvaticaCommonsHttpClientSpnegoImpl.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
public void setGSSCredential(GSSCredential credential) {
  this.authRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO,
      new SPNegoSchemeFactory(STRIP_PORT_ON_SERVER_LOOKUP, USE_CANONICAL_HOSTNAME)).build();

  this.credentialsProvider = new BasicCredentialsProvider();
  if (null != credential) {
    // Non-null credential should be used directly with KerberosCredentials.
    // This is never set by the JDBC driver, nor the tests
    this.credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));
  } else {
    // A null credential implies that the user is logged in via JAAS using the
    // java.security.auth.login.config system property
    this.credentialsProvider.setCredentials(AuthScope.ANY, EmptyCredentials.INSTANCE);
  }
}
 
Example #15
Source File: AccessApi.java    From nifi-swagger-client with Apache License 2.0 5 votes vote down vote up
private HttpClient createSPNEGOHttpClient()  throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    Credentials jaasCredentials = new Credentials() {
        public String getPassword() {
            return null;
        }
        public Principal getUserPrincipal() {
            return null;
        }
    };
    credsProvider.setCredentials(new AuthScope(null, -1, null), jaasCredentials);
    Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create()
            .register(AuthSchemes.SPNEGO,new SPNegoSchemeFactory(true, false))
            .build();

    RequestConfig config = RequestConfig.custom().setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.SPNEGO, AuthSchemes.KERBEROS, AuthSchemes.NTLM)).build();

    HttpClientBuilder httpClientBuilder = HttpClients.custom()
            .setDefaultAuthSchemeRegistry(authSchemeRegistry)
            .setDefaultCredentialsProvider(credsProvider)
            .setDefaultRequestConfig(config);

    if (!this.apiClient.isVerifyingSsl()) {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true).build();
        HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
        httpClientBuilder = httpClientBuilder
                                .setSSLContext(sslContext)
                                .setSSLHostnameVerifier(hostnameVerifier);
    }

    return httpClientBuilder.build();
}
 
Example #16
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 #17
Source File: HttpClient.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example #18
Source File: HttpClientAdapter.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
private Registry<AuthSchemeProvider> getAuthSchemeRegistry() {
    final RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.create();
    registryBuilder.register(AuthSchemes.NTLM, new JCIFSNTLMSchemeFactory())
            .register(AuthSchemes.BASIC, new BasicSchemeFactory())
            .register(AuthSchemes.DIGEST, new DigestSchemeFactory());
    if (Settings.getBooleanProperty("davmail.enableKerberos")) {
        registryBuilder.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
                .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory());
    }

    return registryBuilder.build();
}
 
Example #19
Source File: AuthSchemeProviderLookupBuilderTest.java    From cs-actions with Apache License 2.0 4 votes vote down vote up
@Test
public void buildLookupWithNtlmAuth() {
    AuthSchemeProvider provider = getAuthSchemeProvider(AuthSchemes.NTLM);
    assertThat(provider, instanceOf(AuthSchemeProvider.class));
}
 
Example #20
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 #21
Source File: AuthSchemeProviderLookupBuilderTest.java    From cs-actions with Apache License 2.0 4 votes vote down vote up
@Test
public void buildLookupWithDigestAuth() {
    AuthSchemeProvider provider = getAuthSchemeProvider(AuthSchemes.DIGEST);
    assertThat(provider, instanceOf(DigestSchemeFactory.class));
}
 
Example #22
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 #23
Source File: DefaultHttpClientFactory.java    From knox with Apache License 2.0 4 votes vote down vote up
@Override
public HttpClient createHttpClient(FilterConfig filterConfig) {
  final String serviceRole = filterConfig.getInitParameter(PARAMETER_SERVICE_ROLE);
  HttpClientBuilder builder;
  GatewayConfig gatewayConfig = (GatewayConfig) filterConfig.getServletContext().getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE);
  GatewayServices services = (GatewayServices) filterConfig.getServletContext()
      .getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
  if (gatewayConfig != null && gatewayConfig.isMetricsEnabled()) {
    MetricsService metricsService = services.getService(ServiceType.METRICS_SERVICE);
    builder = metricsService.getInstrumented(HttpClientBuilder.class);
  } else {
    builder = HttpClients.custom();
  }

  // Conditionally set a custom SSLContext
  SSLContext sslContext = createSSLContext(services, filterConfig, serviceRole);
  if(sslContext != null) {
    builder.setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext));
  }

  if (Boolean.parseBoolean(System.getProperty(GatewayConfig.HADOOP_KERBEROS_SECURED))) {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UseJaasCredentials());

    Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
        .register(AuthSchemes.SPNEGO, new KnoxSpnegoAuthSchemeFactory(true))
        .build();

    builder.setDefaultAuthSchemeRegistry(authSchemeRegistry)
        .setDefaultCookieStore(new HadoopAuthCookieStore(gatewayConfig))
        .setDefaultCredentialsProvider(credentialsProvider);
  } else {
    builder.setDefaultCookieStore(new NoCookieStore());
  }

  builder.setKeepAliveStrategy( DefaultConnectionKeepAliveStrategy.INSTANCE );
  builder.setConnectionReuseStrategy( DefaultConnectionReuseStrategy.INSTANCE );
  builder.setRedirectStrategy( new NeverRedirectStrategy() );
  builder.setRetryHandler( new NeverRetryHandler() );

  int maxConnections = getMaxConnections( filterConfig );
  builder.setMaxConnTotal( maxConnections );
  builder.setMaxConnPerRoute( maxConnections );

  builder.setDefaultRequestConfig(getRequestConfig(filterConfig, serviceRole));

  // See KNOX-1530 for details
  builder.disableContentCompression();

  return builder.build();
}
 
Example #24
Source File: XmlRpcFileManagerClient.java    From oodt with Apache License 2.0 4 votes vote down vote up
/**
 * <p> Constructs a new XmlRpcFileManagerClient with the given <code>url</code>. </p>
 *
 * @param url            The url pointer to the xml rpc file manager service.
 * @param testConnection Whether or not to check if server at given url is alive.
 */
public XmlRpcFileManagerClient(final URL url, boolean testConnection)
        throws ConnectionException {
  // set up the configuration, if there is any
  if (System.getProperty("org.apache.oodt.cas.filemgr.properties") != null) {
    String configFile = System
            .getProperty("org.apache.oodt.cas.filemgr.properties");
    LOG.log(Level.INFO,
            "Loading File Manager Configuration Properties from: ["
                    + configFile + "]");
    try {
      System.getProperties().load(
              new FileInputStream(new File(configFile)));
    } catch (Exception e) {
      LOG.log(Level.INFO,
              "Error loading configuration properties from: ["
                      + configFile + "]");
    }

  }

  XmlRpcTransportFactory transportFactory = new XmlRpcTransportFactory() {

    public XmlRpcTransport createTransport()
            throws XmlRpcClientException {

      HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {
        public boolean retryRequest(
                IOException exception,
                int count,
                HttpContext context){
          if (count < Integer
                  .getInteger(
                          "org.apache.oodt.cas.filemgr.system.xmlrpc.connection.retries",
                          3)) {
            try {
              Thread
                      .sleep(Integer
                              .getInteger(
                                      "org.apache.oodt.cas.filemgr.system.xmlrpc.connection.retry.interval.seconds",
                                      0) * 1000);
              return true;
            } catch (Exception ignored) {
            }
          }
          return false;
        }
      };
      RequestConfig config = RequestConfig.custom()
              .setSocketTimeout(Integer
                      .getInteger(
                              "org.apache.oodt.cas.filemgr.system.xmlrpc.connectionTimeout.minutes",
                              20) * 60 * 1000)
              .setConnectTimeout(Integer
                      .getInteger(
                              "org.apache.oodt.cas.filemgr.system.xmlrpc.requestTimeout.minutes",
                              60) * 60 * 1000)
              .build();
      Registry<AuthSchemeProvider> r = RegistryBuilder.<AuthSchemeProvider>create().build();
      HttpClient client = HttpClients.custom().setRetryHandler(myRetryHandler).setDefaultAuthSchemeRegistry(r).setDefaultRequestConfig(config).build();

      CommonsXmlRpcTransport transport = new CommonsXmlRpcTransport(url, client);
      transport
              .setConnectionTimeout(Integer
                      .getInteger(
                              "org.apache.oodt.cas.filemgr.system.xmlrpc.connectionTimeout.minutes",
                              20) * 60 * 1000);
      transport
              .setTimeout(Integer
                      .getInteger(
                              "org.apache.oodt.cas.filemgr.system.xmlrpc.requestTimeout.minutes",
                              60) * 60 * 1000);

      return transport;
    }

    public void setProperty(String arg0, Object arg1) {
    }

  };

  client = new XmlRpcClient(url, transportFactory);
  fileManagerUrl = url;

  if (testConnection && !isAlive()) {
    throw new ConnectionException("Exception connecting to filemgr: ["
            + this.fileManagerUrl + "]");
  }

}
 
Example #25
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 #26
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 #27
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 #28
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 #29
Source File: SdcSolrHttpClientBuilder.java    From datacollector with Apache License 2.0 4 votes vote down vote up
static SolrHttpClientBuilder create() {
  SolrHttpClientBuilder solrHttpClientBuilder = SolrHttpClientBuilder.create();

  final String useSubjectCredentialsProperty = USE_SUBJECT_CREDENTIALS_PROPERTY;
  String useSubjectCredentialsValue = System.getProperty(useSubjectCredentialsProperty);

  if (useSubjectCredentialsValue == null) {
    System.setProperty(useSubjectCredentialsProperty, FALSE);
  } else if (!useSubjectCredentialsValue.toLowerCase(Locale.ROOT).equals(FALSE)) {
    LOG.warn(String.format(
        "System Property: %s set to: %s not false. SPNego authentication may not be successful.",
        useSubjectCredentialsProperty,
        useSubjectCredentialsValue
    ));
  }

  solrHttpClientBuilder.setAuthSchemeRegistryProvider(() -> RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO,
      new SPNegoSchemeFactory(true)
  ).build());

  SolrPortAwareCookieSpecFactory cookieFactory = new SolrPortAwareCookieSpecFactory();
  solrHttpClientBuilder.setCookieSpecRegistryProvider(() -> RegistryBuilder.<CookieSpecProvider>create().register(SolrPortAwareCookieSpecFactory.POLICY_NAME,
      cookieFactory
  ).build());

  Credentials jassCredentials = new Credentials() {
    public String getPassword() {
      return null;
    }

    public Principal getUserPrincipal() {
      return null;
    }
  };

  CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(AuthScope.ANY, jassCredentials);
  solrHttpClientBuilder.setDefaultCredentialsProvider(() -> credentialsProvider);

  return solrHttpClientBuilder;
}
 
Example #30
Source File: WebServicesClient.java    From attic-apex-core with Apache License 2.0 4 votes vote down vote up
private static void setupHttpAuthScheme(String httpScheme, AuthSchemeProvider provider, AuthScope authScope, Credentials credentials)
{
  registryBuilder.register(httpScheme, provider);
  credentialsProvider.setCredentials(authScope, credentials);
}