org.apache.http.client.config.AuthSchemes Java Examples

The following examples show how to use org.apache.http.client.config.AuthSchemes. 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: WebServicesClientTest.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
public static void checkUserCredentials(String username, String password, AuthScheme authScheme) throws NoSuchFieldException,
    IllegalAccessException
{
  CredentialsProvider provider = getCredentialsProvider();
  String httpScheme = AuthScope.ANY_SCHEME;
  if (authScheme == AuthScheme.BASIC) {
    httpScheme = AuthSchemes.BASIC;
  } else if (authScheme == AuthScheme.DIGEST) {
    httpScheme = AuthSchemes.DIGEST;
  }
  AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, httpScheme);
  Credentials credentials = provider.getCredentials(authScope);
  Assert.assertNotNull("Credentials", credentials);
  Assert.assertTrue("Credentials type is user", UsernamePasswordCredentials.class.isAssignableFrom(credentials.getClass()));
  UsernamePasswordCredentials pwdCredentials = (UsernamePasswordCredentials)credentials;
  Assert.assertEquals("Username", username, pwdCredentials.getUserName());
  Assert.assertEquals("Password", password, pwdCredentials.getPassword());
}
 
Example #2
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 #3
Source File: Winrm4jTool.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public Winrm4jTool(ConfigBag config) {
    this.bag = checkNotNull(config, "config bag");
    host = getRequiredConfig(config, PROP_HOST);
    port = config.get(PROP_PORT);
    useSecureWinrm = config.get(USE_HTTPS_WINRM);
    authenticationScheme = config.get(USE_NTLM) ? AuthSchemes.NTLM : null;
    computerName = Strings.isNonBlank(config.get(COMPUTER_NAME)) ? config.get(COMPUTER_NAME) : null;
    user = getRequiredConfig(config, PROP_USER);
    password = getRequiredConfig(config, PROP_PASSWORD);
    execTries = getRequiredConfig(config, PROP_EXEC_TRIES);
    execRetryDelay = getRequiredConfig(config, PROP_EXEC_RETRY_DELAY);
    logCredentials = getRequiredConfig(config, LOG_CREDENTIALS);
    operationTimeout = config.get(OPERATION_TIMEOUT);
    retriesOfNetworkFailures = config.get(RETRIES_OF_NETWORK_FAILURES);
    environment = config.get(ENVIRONMENT);
}
 
Example #4
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 #5
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 #6
Source File: HttpClientAdapter.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
private RequestConfig getRequestConfig() {
    HashSet<String> authSchemes = new HashSet<>();
    authSchemes.add(AuthSchemes.NTLM);
    authSchemes.add(AuthSchemes.BASIC);
    authSchemes.add(AuthSchemes.DIGEST);
    if (Settings.getBooleanProperty("davmail.enableKerberos")) {
        authSchemes.add(AuthSchemes.SPNEGO);
        authSchemes.add(AuthSchemes.KERBEROS);
    }
    return RequestConfig.custom()
            // socket connect timeout
            .setConnectTimeout(Settings.getIntProperty("davmail.exchange.connectionTimeout", 10) * 1000)
            // inactivity timeout
            .setSocketTimeout(Settings.getIntProperty("davmail.exchange.soTimeout", 120) * 1000)
            .setTargetPreferredAuthSchemes(authSchemes)
            .build();
}
 
Example #7
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 #8
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 #9
Source File: ApacheDefaultHttpRequestFactoryTest.java    From ibm-cos-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void request_has_proxy_config_when_proxy_auth_enabled() throws Exception {
    List<ProxyAuthenticationMethod> authMethods = Arrays.asList(ProxyAuthenticationMethod.BASIC,
                                                                ProxyAuthenticationMethod.DIGEST,
                                                                ProxyAuthenticationMethod.KERBEROS,
                                                                ProxyAuthenticationMethod.NTLM,
                                                                ProxyAuthenticationMethod.SPNEGO);
    List<String> expectedAuthMethods = Arrays.asList(AuthSchemes.BASIC,
                                                     AuthSchemes.DIGEST,
                                                     AuthSchemes.KERBEROS,
                                                     AuthSchemes.NTLM,
                                                     AuthSchemes.SPNEGO);

    ClientConfiguration configuration = new ClientConfiguration().withProxyHost("localhost")
                                                                 .withProxyPort(80)
                                                                 .withProxyUsername("user")
                                                                 .withProxyPassword("password")
                                                                 .withProxyAuthenticationMethods(authMethods);
    HttpClientSettings settings = HttpClientSettings.adapt(configuration);
    HttpRequestBase requestBase = requestFactory.create(newDefaultRequest(HttpMethodName.POST), settings);
    Assert.assertEquals(expectedAuthMethods, requestBase.getConfig().getProxyPreferredAuthSchemes());
}
 
Example #10
Source File: HttpManagementInterface.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static CloseableHttpClient createHttpClient(String host, int port, String username, String password) {
    SSLContext sslContext = org.apache.http.ssl.SSLContexts.createDefault();
                SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslConnectionSocketFactory)
                    .build();
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(host, port, MANAGEMENT_REALM, AuthSchemes.DIGEST),
                    new UsernamePasswordCredentials(username, password));

    return HttpClientBuilder.create()
                    .setConnectionManager(new PoolingHttpClientConnectionManager(registry))
                    .setRetryHandler(new StandardHttpRequestRetryHandler(5, true))
                    .setDefaultCredentialsProvider(credentialsProvider)
                    .build();
}
 
Example #11
Source File: HttpGenericOperationUnitTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static CloseableHttpClient createHttpClient(String host, int port, String username, String password) {
    try {
        SSLContext sslContext = SSLContexts.createDefault();
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionSocketFactory)
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .build();
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host, port, MANAGEMENT_REALM, AuthSchemes.DIGEST),
                new UsernamePasswordCredentials(username, password));
        PoolingHttpClientConnectionManager connectionPool = new PoolingHttpClientConnectionManager(registry);
        HttpClientBuilder.create().setConnectionManager(connectionPool).build();
        return HttpClientBuilder.create()
                .setConnectionManager(connectionPool)
                .setRetryHandler(new StandardHttpRequestRetryHandler(5, true))
                .setDefaultCredentialsProvider(credsProvider).build();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #12
Source File: ResponseStreamTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private HttpClient getHttpClient(URL url) {
    shutdownHttpClient();
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort(), "ManagementRealm", AuthSchemes.DIGEST),
            new UsernamePasswordCredentials(DomainLifecycleUtil.SLAVE_HOST_USERNAME, DomainLifecycleUtil.SLAVE_HOST_PASSWORD));

    httpClient = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(credsProvider)
            .build();

    return httpClient;
}
 
Example #13
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 #14
Source File: ResponseAttachmentTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private CloseableHttpClient createHttpClient(URL url) {

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort(), "ManagementRealm", AuthSchemes.DIGEST),
                new UsernamePasswordCredentials(Authentication.USERNAME, Authentication.PASSWORD));
        return HttpClientBuilder.create()
                .setDefaultCredentialsProvider(credsProvider)
                .build();
    }
 
Example #15
Source File: IdeHttpClientHelpers.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Install credentials for IDE-wide proxy if usage of proxy and proxy authentication were enabled in {@link HttpConfigurable}.
 *
 * @param provider HttpClient's credentials provider used to configure new client
 * @see #setProxyCredentialsForUrlIfEnabled(CredentialsProvider, String)
 */
public static void setProxyCredentialsIfEnabled(@Nonnull CredentialsProvider provider) {
  if (isHttpProxyEnabled() && isProxyAuthenticationEnabled()) {
    final String ntlmUserPassword = getProxyLogin().replace('\\', '/') + ":" + getProxyPassword();
    provider.setCredentials(new AuthScope(getProxyHost(), getProxyPort(), AuthScope.ANY_REALM, AuthSchemes.NTLM),
                            new NTCredentials(ntlmUserPassword));
    provider.setCredentials(new AuthScope(getProxyHost(), getProxyPort()),
                            new UsernamePasswordCredentials(getProxyLogin(), getProxyPassword()));
  }
}
 
Example #16
Source File: CredentialsProviderBuilderTest.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
@Test
public void createNtlmCredentialsProvider() {
    CredentialsProvider credentialsProvider = getCredentialsProvider(AuthSchemes.NTLM);
    Credentials credentials = credentialsProvider.getCredentials(new AuthScope("host", 80));

    assertThat(credentials, instanceOf(NTCredentials.class));
    NTCredentials ntCredentials = (NTCredentials) credentials;
    assertEquals("DOMAIN", ntCredentials.getDomain());
    assertEquals("HOST", ntCredentials.getWorkstation());
    assertEquals("pass", ntCredentials.getPassword());
    Credentials proxyCredentials = credentialsProvider.getCredentials(new AuthScope("proxy", 8080));
    assertThat(proxyCredentials, instanceOf(UsernamePasswordCredentials.class));
    UsernamePasswordCredentials userCredentials = (UsernamePasswordCredentials) proxyCredentials;
    assertEquals("proxyUsername", userCredentials.getUserName());
}
 
Example #17
Source File: CredentialsProviderBuilderTest.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
@Test
public void createKerberosCredentialsProvider() {
    CredentialsProvider credentialsProvider = getCredentialsProvider(AuthSchemes.KERBEROS);
    Credentials credentials = credentialsProvider.getCredentials(new AuthScope("host", 80));

    assertThat(credentials, instanceOf(Credentials.class));
}
 
Example #18
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 #19
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 #20
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 #21
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 #22
Source File: HttpClientConfigurator.java    From bintray-client-java with Apache License 2.0 5 votes vote down vote up
private void configureProxy(ProxyConfig proxy) {
    if (proxy != null) {
        config.setProxy(new HttpHost(proxy.getHost(), proxy.getPort()));
        if (proxy.getUserName() != null) {
            Credentials creds = null;
            if (proxy.getNtDomain() == null) {
                creds = new UsernamePasswordCredentials(proxy.getUserName(), proxy.getPassword());
                List<String> authPrefs = Arrays.asList(AuthSchemes.DIGEST, AuthSchemes.BASIC, AuthSchemes.NTLM);
                config.setProxyPreferredAuthSchemes(authPrefs);

                // preemptive proxy authentication
                builder.addInterceptorFirst(new ProxyPreemptiveAuthInterceptor());
            } else {
                try {
                    String ntHost =
                            StringUtils.isBlank(proxy.getNtHost()) ? InetAddress.getLocalHost().getHostName() :
                                    proxy.getNtHost();
                    creds = new NTCredentials(proxy.getUserName(), proxy.getPassword(), ntHost, proxy.getNtDomain());
                } catch (UnknownHostException e) {
                    log.error("Failed to determine required local hostname for NTLM credentials.", e);
                }
            }
            if (creds != null) {
                credsProvider.setCredentials(
                        new AuthScope(proxy.getHost(), proxy.getPort(), AuthScope.ANY_REALM), creds);
                if (proxy.getRedirectToHosts() != null) {
                    for (String hostName : proxy.getRedirectToHosts()) {
                        credsProvider.setCredentials(
                                new AuthScope(hostName, AuthScope.ANY_PORT, AuthScope.ANY_REALM), creds);
                    }
                }
            }
        }
    }
}
 
Example #23
Source File: AbstractKerberosTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void initHttpClient(boolean useSpnego) {
    if (client != null) {
        cleanupApacheHttpClient();
    }
    
    DefaultHttpClient httpClient = (DefaultHttpClient) new HttpClientBuilder()
            .disableCookieCache(false)
            .build();

    httpClient.getAuthSchemes().register(AuthSchemes.SPNEGO, spnegoSchemeFactory);

    if (useSpnego) {
        Credentials fake = new Credentials() {

            @Override
            public String getPassword() {
                return null;
            }

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

        };

        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(null, -1, null),
                fake);
    }
    ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
    client = new ResteasyClientBuilder().httpEngine(engine).build();
}
 
Example #24
Source File: TdsMonitor.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public TdsMonitor(ucar.util.prefs.PreferencesExt prefs, JFrame parentFrame) throws HTTPException {
  this.mainPrefs = prefs;
  this.parentFrame = parentFrame;

  fileChooser = new FileManager(parentFrame, null, null, (PreferencesExt) prefs.node("FileManager"));

  // the top UI
  tabbedPane = new JTabbedPane(JTabbedPane.TOP);
  managePanel = new ManagePanel((PreferencesExt) mainPrefs.node("ManageLogs"));
  accessLogPanel = new AccessLogPanel((PreferencesExt) mainPrefs.node("LogTable"));
  servletLogPanel = new ServletLogPanel((PreferencesExt) mainPrefs.node("ServletLogPanel"));
  urlDump = new URLDumpPane((PreferencesExt) mainPrefs.node("urlDump"));

  tabbedPane.addTab("ManageLogs", managePanel);
  tabbedPane.addTab("AccessLogs", accessLogPanel);
  tabbedPane.addTab("ServletLogs", servletLogPanel);
  tabbedPane.addTab("UrlDump", urlDump);
  tabbedPane.setSelectedIndex(0);

  setLayout(new BorderLayout());
  add(tabbedPane, BorderLayout.CENTER);

  CredentialsProvider provider = new UrlAuthenticatorDialog(null);
  try {
    HTTPSession.setGlobalCredentialsProvider(provider, AuthSchemes.BASIC);
  } catch (HTTPException e) {
    System.err.println("Failed to set credentials");
  }
  HTTPSession.setGlobalUserAgent("TdsMonitor");
}
 
Example #25
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 #26
Source File: WebServicesClient.java    From Bats with Apache License 2.0 5 votes vote down vote up
public static void initAuth(ConfigProvider configuration)
{
  // Setting up BASIC and DIGEST auth
  setupUserPassAuthScheme(AuthScheme.BASIC, AuthSchemes.BASIC, new BasicSchemeFactory(), configuration);
  setupUserPassAuthScheme(AuthScheme.DIGEST, AuthSchemes.DIGEST, new DigestSchemeFactory(), configuration);

  // Adding kerberos standard auth
  setupHttpAuthScheme(AuthSchemes.KERBEROS, new KerberosSchemeFactory(), AuthScope.ANY, DEFAULT_TOKEN_CREDENTIALS);

  authRegistry = registryBuilder.build();
}
 
Example #27
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 #28
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 #29
Source File: BackportWindowsNegotiateScheme.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
public BackportWindowsNegotiateScheme(final String scheme, final String servicePrincipalName) {
    super();

    this.scheme = (scheme == null) ? AuthSchemes.SPNEGO : scheme;
    this.challenge = null;
    this.continueNeeded = true;
    this.servicePrincipalName = servicePrincipalName;

    if(this.log.isDebugEnabled()) {
        this.log.debug("Created WindowsNegotiateScheme using " + this.scheme);
    }
}
 
Example #30
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;
}