org.apache.http.auth.NTCredentials Java Examples

The following examples show how to use org.apache.http.auth.NTCredentials. 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: WebServiceNtlmSender.java    From iaf with Apache License 2.0 6 votes vote down vote up
@Override
public void configure() throws ConfigurationException {
	super.configure();

	HttpParams httpParameters = new BasicHttpParams();
	HttpConnectionParams.setConnectionTimeout(httpParameters, getTimeout());
	HttpConnectionParams.setSoTimeout(httpParameters, getTimeout());
	httpClient = new DefaultHttpClient(connectionManager, httpParameters);
	httpClient.getAuthSchemes().register("NTLM", new NTLMSchemeFactory());
	CredentialFactory cf = new CredentialFactory(getAuthAlias(), getUserName(), getPassword());
	httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new NTCredentials(cf.getUsername(), cf.getPassword(), Misc.getHostname(), getAuthDomain()));
	if (StringUtils.isNotEmpty(getProxyHost())) {
		HttpHost proxy = new HttpHost(getProxyHost(), getProxyPort());
		httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
	}
}
 
Example #2
Source File: AuthenticationHelper.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static Credentials getCredentials( final String user,
                                         final String password ) {
  if ( StringUtils.isEmpty( user ) ) {
    return null;
  }

  final Configuration config = ReportDesignerBoot.getInstance().getGlobalConfig();
  if ( "true".equals( config.getConfigProperty( NT_AUTH_CONFIGKEY, "false" ) ) == false ) {
    return new UsernamePasswordCredentials( user, password );
  }

  final int domainIdx = user.indexOf( DOMAIN_SEPARATOR );
  if ( domainIdx == -1 ) {
    return new UsernamePasswordCredentials( user, password );
  }
  try {
    final String domain = user.substring( 0, domainIdx );
    final String username = user.substring( domainIdx + 1 );
    final String host = InetAddress.getLocalHost().getHostName();
    return new NTCredentials( username, password, host, domain );
  } catch ( UnknownHostException uhe ) {
    return new UsernamePasswordCredentials( user, password );
  }
}
 
Example #3
Source File: HttpQueryBackend.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static Credentials getCredentials( final String user,
                                          final String password ) {
  if ( StringUtils.isEmpty( user ) ) {
    return null;
  }

  final int domainIdx = user.indexOf( DOMAIN_SEPARATOR );
  if ( domainIdx == -1 ) {
    return new UsernamePasswordCredentials( user, password );
  }
  try {
    final String domain = user.substring( 0, domainIdx );
    final String username = user.substring( domainIdx + 1 );
    final String host = InetAddress.getLocalHost().getHostName();
    return new NTCredentials( username, password, host, domain );
  } catch ( UnknownHostException uhe ) {
    return new UsernamePasswordCredentials( user, password );
  }
}
 
Example #4
Source File: AuthHelperTest.java    From azure-devops-intellij with MIT License 6 votes vote down vote up
@Test
public void getCredentials() {
    // Basic TFS
    final AuthenticationInfo info = new AuthenticationInfo("name1", "pass1", "server1", "display1");
    final Credentials credentials = AuthHelper.getCredentials(ServerContext.Type.TFS, info);
    Assert.assertTrue(credentials instanceof NTCredentials);
    Assert.assertEquals("name1", credentials.getUserPrincipal().getName());
    Assert.assertEquals("pass1", credentials.getPassword());

    // Basic VSO
    final AuthenticationInfo info2 = new AuthenticationInfo("name2", "pass2", "server2", "display2");
    final Credentials credentials2 = AuthHelper.getCredentials(ServerContext.Type.VSO, info2);
    Assert.assertTrue(credentials2 instanceof UsernamePasswordCredentials);
    Assert.assertEquals("name2", credentials2.getUserPrincipal().getName());
    Assert.assertEquals("pass2", credentials2.getPassword());

    // domain parsing
    createAndVerifyNTCredentials("domain", "name", "domain/name", "pass");
    createAndVerifyNTCredentials("domain", "name", "domain\\name", "pass");
    createAndVerifyNTCredentials("domain", "name", "name@domain", "pass");
}
 
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: HttpClientHandler.java    From ant-ivy with Apache License 2.0 5 votes vote down vote up
private static Credentials createCredentials(final String username, final String password) {
    final String user;
    final String domain;
    int backslashIndex = username.indexOf('\\');
    if (backslashIndex >= 0) {
        user = username.substring(backslashIndex + 1);
        domain = username.substring(0, backslashIndex);
    } else {
        user = username;
        domain = System.getProperty("http.auth.ntlm.domain", "");
    }
    return new NTCredentials(user, password, HostUtil.getLocalHostName(), domain);
}
 
Example #7
Source File: PreemptiveAuthHttpClientConnectionTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
private static void createNTCredentials(final String inputUserName, final String inputPassword, final String expectedDomain, final String expectedUserName, final String expectedPassword) {

        final NTCredentials actual = PreemptiveAuthHttpClientConnection.createNTCredentials(inputUserName, inputPassword);

        assertEquals(expectedDomain, actual.getDomain());
        assertEquals(expectedUserName, actual.getUserName());
        assertEquals(expectedPassword, actual.getPassword());
    }
 
Example #8
Source File: PreemptiveAuthHttpClientConnection.java    From git-client-plugin with MIT License 5 votes vote down vote up
static NTCredentials createNTCredentials(final String userName, final String password) {
    final int firstAt = userName.indexOf('@');
    final int firstSlash = userName.indexOf('/');
    final int firstBackSlash = userName.indexOf('\\');

    final String user, domain;
    if (firstAt != -1) {
        // [email protected]
        user = userName.substring(0, firstAt);
        domain = userName.substring(firstAt + 1);
    }
    else if (firstSlash != -1) {
        // WALKER/cnorris
        domain = userName.substring(0, firstSlash);
        user = userName.substring(firstSlash + 1);
    }
    else if (firstBackSlash != -1) {
        // WALKER\cnorris
        domain = userName.substring(0, firstBackSlash);
        user = userName.substring(firstBackSlash + 1);
    }
    else {
        user = userName;
        domain = null;
    }

    return new NTCredentials(user, password, null, domain);
}
 
Example #9
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 #10
Source File: WebAuthentication.java    From fess with Apache License 2.0 5 votes vote down vote up
private Credentials getCredentials() {
    if (StringUtil.isEmpty(getUsername())) {
        throw new CrawlerSystemException("username is empty.");
    }

    if (Constants.NTLM.equals(getProtocolScheme())) {
        final Map<String, String> parameterMap = ParameterUtil.parse(getParameters());
        final String workstation = parameterMap.get("workstation");
        final String domain = parameterMap.get("domain");
        return new NTCredentials(getUsername(), getPassword(), workstation == null ? StringUtil.EMPTY : workstation,
                domain == null ? StringUtil.EMPTY : domain);
    }

    return new UsernamePasswordCredentials(getUsername(), getPassword() == null ? StringUtil.EMPTY : getPassword());
}
 
Example #11
Source File: AuthenticationHelper.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static Credentials getCredentials( final String url,
                                          final AuthenticationStore store ) {
  final String user = store.getUsername( url );
  if ( user == null ) {
    return null;
  }

  final String password = store.getPassword( url );

  final Configuration config = ReportDesignerBoot.getInstance().getGlobalConfig();
  if ( "true".equals( config.getConfigProperty( NT_AUTH_CONFIGKEY, "false" ) ) == false ) {
    return new UsernamePasswordCredentials( user, password );
  }

  final int domainIdx = user.indexOf( DOMAIN_SEPARATOR );
  if ( domainIdx == -1 ) {
    return new UsernamePasswordCredentials( user, password );
  }
  try {
    final String domain = user.substring( 0, domainIdx );
    final String username = user.substring( domainIdx + 1 );
    final String host = InetAddress.getLocalHost().getHostName();
    return new NTCredentials( username, password, host, domain );
  } catch ( UnknownHostException uhe ) {
    return new UsernamePasswordCredentials( user, password );
  }
}
 
Example #12
Source File: UrlDownloaderUsingNtlmCredentials.java    From estatio with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init(Map<String,String> props) throws UnknownHostException {

    String user = null;
    String ntDomain = null;

    final String userProp = PREFIX + "user";
    final String fullyQualifiedUser = props.get(userProp);
    if(fullyQualifiedUser != null) {
        final List<String> userParts = Splitter.on(slash()).splitToList(fullyQualifiedUser);
        ntDomain = userParts.get(0);
        user = userParts.get(1);
    }

    String password = props.get(PREFIX + "password");
    host = props.get(PREFIX + "host");

    if( user != null && password != null && ntDomain != null && host != null) {

        workstation = InetAddress.getLocalHost().getHostName();

        // thread-safe according to HTTP Client
        httpclient = HttpClientBuilder.create().build();
        // implementations are required to be thread-safe, apparently
        credsProvider = new BasicCredentialsProvider();

        // immutable, so okay to reuse
        final NTCredentials credentials = new NTCredentials(user, password, workstation, ntDomain);
        credsProvider.setCredentials(AuthScope.ANY, credentials);
    }
}
 
Example #13
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 #14
Source File: BceHttpClient.java    From bce-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a new BCE client using the specified client configuration options (ex: max retry attempts, proxy
 * settings, etc), and request metric collector.
 *
 * @param config Configuration options specifying how this client will communicate with BCE (ex: proxy settings,
 * retry count, etc.).
 * @param signer signer used to sign http requests
 * @throws java.lang.IllegalArgumentException If config or signer is null.
 */
public BceHttpClient(BceClientConfiguration config, Signer signer) {
    checkNotNull(config, "config should not be null.");
    checkNotNull(signer, "signer should not be null.");
    this.config = config;
    this.signer = signer;
    this.connectionManager = this.createHttpClientConnectionManager();
    this.httpClient = this.createHttpClient(this.connectionManager);
    IdleConnectionReaper.registerConnectionManager(this.connectionManager);

    this.requestConfigBuilder = RequestConfig.custom();
    this.requestConfigBuilder.setConnectTimeout(config.getConnectionTimeoutInMillis());
    this.requestConfigBuilder.setStaleConnectionCheckEnabled(true);
    if (config.getLocalAddress() != null) {
        this.requestConfigBuilder.setLocalAddress(config.getLocalAddress());
    }

    String proxyHost = config.getProxyHost();
    int proxyPort = config.getProxyPort();
    if (proxyHost != null && proxyPort > 0) {
        this.proxyHttpHost = new HttpHost(proxyHost, proxyPort);
        this.requestConfigBuilder.setProxy(this.proxyHttpHost);

        this.credentialsProvider = new BasicCredentialsProvider();
        String proxyUsername = config.getProxyUsername();
        String proxyPassword = config.getProxyPassword();
        String proxyDomain = config.getProxyDomain();
        String proxyWorkstation = config.getProxyWorkstation();
        if (proxyUsername != null && proxyPassword != null) {
            this.credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword,
                            proxyWorkstation, proxyDomain));
        }
    }
}
 
Example #15
Source File: NTLMAuthHttpClientFactory.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public DefaultHttpClient create(final HttpMethod method, final URI uri) {
  final DefaultHttpClient httpclient = super.create(method, uri);

  final CredentialsProvider credsProvider = new BasicCredentialsProvider();
  credsProvider.setCredentials(AuthScope.ANY,
          new NTCredentials(username, password, workstation, domain));

  httpclient.setCredentialsProvider(credsProvider);

  return httpclient;
}
 
Example #16
Source File: AuthHelperTest.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
private void createAndVerifyNTCredentials(final String domain, final String name, final String domainName, final String pass) {
    final AuthenticationInfo info = new AuthenticationInfo(domainName, pass, "server", "display");
    final Credentials credentials = AuthHelper.getCredentials(ServerContext.Type.TFS, info);
    Assert.assertTrue(credentials instanceof NTCredentials);
    Assert.assertEquals(name, ((NTCredentials) credentials).getUserName());
    Assert.assertEquals(domain, ((NTCredentials) credentials).getDomain().toLowerCase());
    if(SystemHelper.getComputerName() != null) { //coming back null when running from command line on Mac, works inside IDE
        Assert.assertEquals(SystemHelper.getComputerName().toLowerCase(), ((NTCredentials) credentials).getWorkstation().toLowerCase());
    }
    Assert.assertEquals(pass, credentials.getPassword());
}
 
Example #17
Source File: AuthHelper.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
/**
 * Returns an NTCredentials object for given username and password
 *
 * @param userName
 * @param password
 * @return
 */
public static NTCredentials getNTCredentials(final String userName, final String password) {
    assert userName != null;
    assert password != null;

    String user = userName;
    String domain = "";
    final String workstation = SystemHelper.getComputerName();

    // If the username has a backslash, then the domain is the first part and the username is the second part
    if (userName.contains("\\")) {
        String[] parts = userName.split("[\\\\]");
        if (parts.length == 2) {
            domain = parts[0];
            user = parts[1];
        }
    } else if (userName.contains("/")) {
        // If the username has a slash, then the domain is the first part and the username is the second part
        String[] parts = userName.split("[/]");
        if (parts.length == 2) {
            domain = parts[0];
            user = parts[1];
        }
    } else if (userName.contains("@")) {
        // If the username has an asterisk, then the domain is the second part and the username is the first part
        String[] parts = userName.split("[@]");
        if (parts.length == 2) {
            user = parts[0];
            domain = parts[1];
        }
    }

    return new org.apache.http.auth.NTCredentials(user, password, workstation, domain);
}
 
Example #18
Source File: HttpFactory.java    From aliyun-tablestore-java-sdk with Apache License 2.0 5 votes vote down vote up
public static CloseableHttpAsyncClient createHttpAsyncClient(
        ClientConfiguration config, PoolingNHttpClientConnectionManager cm) {
    HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom();
    httpClientBuilder.setConnectionManager(cm);
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(config.getConnectionTimeoutInMillisecond())
            .setSocketTimeout(config.getSocketTimeoutInMillisecond()).build();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);
    httpClientBuilder.setUserAgent(Constants.USER_AGENT);
    httpClientBuilder.disableCookieManagement();

    String proxyHost = config.getProxyHost();
    int proxyPort = config.getProxyPort();
    if (proxyHost != null) {
        if (proxyPort <= 0) {
            throw new ClientException("The proxy port is invalid. Please check your configuration.");
        }
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        httpClientBuilder.setProxy(proxy);
        String proxyUsername = config.getProxyUsername();
        String proxyPassword = config.getProxyPassword();
        if (proxyUsername != null && proxyPassword != null) {
            String proxyDomain = config.getProxyDomain();
            String proxyWorkstation = config.getProxyWorkstation();
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(
                new AuthScope(proxyHost, proxyPort),
                new NTCredentials(
                    proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
            httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
        }
    }

    return httpClientBuilder.build();
}
 
Example #19
Source File: ApacheUtils.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new instance of NTCredentials used for proxy authentication.
 */
private static Credentials newNTCredentials(HttpClientSettings settings) {
    return new NTCredentials(settings.getProxyUsername(),
            settings.getProxyPassword(),
            settings.getProxyWorkstation(),
            settings.getProxyDomain());
}
 
Example #20
Source File: ApacheUtils.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new instance of NTCredentials used for proxy authentication.
 */
private static Credentials newNtCredentials(ProxyConfiguration proxyConfiguration) {
    return new NTCredentials(proxyConfiguration.username(),
                             proxyConfiguration.password(),
                             proxyConfiguration.ntlmWorkstation(),
                             proxyConfiguration.ntlmDomain());
}
 
Example #21
Source File: RemoteProxy.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 5 votes vote down vote up
public static HttpCommandExecutor getProxyExecutor(URL url, Properties prop) {

        prop = decrypt(prop);

        String proxyHost = prop.getProperty("proxyHost");
        int proxyPort = Integer.valueOf(prop.getProperty("proxyPort"));
        String proxyUserDomain = prop.getProperty("proxyUserDomain");
        String proxyUser = prop.getProperty("proxyUser");
        String proxyPassword = prop.getProperty("proxyPassword");

        HttpClientBuilder builder = HttpClientBuilder.create();
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();

        credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                new NTCredentials(proxyUser, proxyPassword, getWorkstation(), proxyUserDomain));
        if (url.getUserInfo() != null && !url.getUserInfo().isEmpty()) {
            credsProvider.setCredentials(new AuthScope(url.getHost(), (url.getPort() > 0 ? url.getPort() : url.getDefaultPort())),
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
        }
        builder.setProxy(proxy);
        builder.setDefaultCredentialsProvider(credsProvider);
        //HttpClient.Factory factory = new SimpleHttpClientFactory(builder);
        HttpClient.Factory factory = new SimpleHttpClientFactory(new okhttp3.OkHttpClient.Builder());

        return new HttpCommandExecutor(new HashMap<>(), url, factory);

    }
 
Example #22
Source File: HttpUtils.java    From jmeter-bzm-plugins with Apache License 2.0 5 votes vote down vote up
private static AbstractHttpClient createHTTPClient() {
    AbstractHttpClient client = new DefaultHttpClient();
    String proxyHost = System.getProperty("https.proxyHost", "");
    if (!proxyHost.isEmpty()) {
        int proxyPort = Integer.parseInt(System.getProperty("https.proxyPort", "-1"));
        log.info("Using proxy " + proxyHost + ":" + proxyPort);
        HttpParams params = client.getParams();
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        String proxyUser = System.getProperty(JMeter.HTTP_PROXY_USER, JMeterUtils.getProperty(JMeter.HTTP_PROXY_USER));
        if (proxyUser != null) {
            log.info("Using authenticated proxy with username: " + proxyUser);
            String proxyPass = System.getProperty(JMeter.HTTP_PROXY_PASS, JMeterUtils.getProperty(JMeter.HTTP_PROXY_PASS));

            String localHost;
            try {
                localHost = InetAddress.getLocalHost().getCanonicalHostName();
            } catch (Throwable e) {
                log.error("Failed to get local host name, defaulting to 'localhost'", e);
                localHost = "localhost";
            }

            AuthScope authscope = new AuthScope(proxyHost, proxyPort);
            String proxyDomain = JMeterUtils.getPropDefault("http.proxyDomain", "");
            NTCredentials credentials = new NTCredentials(proxyUser, proxyPass, localHost, proxyDomain);
            client.getCredentialsProvider().setCredentials(authscope, credentials);
        }
    }
    return client;
}
 
Example #23
Source File: HttpClientAdapter.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
public void setCredentials(String username, String password) {
    parseUserName(username);
    if (userid != null && password != null) {
        NTCredentials credentials = new NTCredentials(userid, password, WORKSTATION_NAME, domain);
        provider.setCredentials(AuthScope.ANY, credentials);
    }
}
 
Example #24
Source File: DefaultCredentialsProvider.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public synchronized void setCredentials(final AuthScope authscope, final Credentials credentials) {
    if (authscope == null) {
        throw new IllegalArgumentException("Authentication scope may not be null");
    }

    if ((credentials instanceof UsernamePasswordCredentials) || (credentials instanceof NTCredentials)) {
        credentialsMap_.put(new AuthScopeProxy(authscope), credentials);
        return;
    }

    throw new IllegalArgumentException("Unsupported Credential type: " + credentials.getClass().getName());
}
 
Example #25
Source File: HttpFactory.java    From mq-http-java-sdk with MIT License 4 votes vote down vote up
public static CloseableHttpAsyncClient createHttpAsyncClient(
        PoolingNHttpClientConnectionManager connManager,
        ClientConfiguration config) {
    HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom()
            .setConnectionManager(connManager);

    // Set proxy if set.
    String proxyHost = config.getProxyHost();
    int proxyPort = config.getProxyPort();

    if (proxyHost != null && proxyPort > 0) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);

        httpClientBuilder.setProxy(proxy);

        String proxyUsername = config.getProxyUsername();
        String proxyPassword = config.getProxyPassword();

        if (proxyUsername != null && proxyPassword != null) {
            String proxyDomain = config.getProxyDomain();
            String proxyWorkstation = config.getProxyWorkstation();

            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

            credentialsProvider.setCredentials(new AuthScope(proxy),
                    new NTCredentials(proxyUsername, proxyPassword,
                            proxyWorkstation, proxyDomain)
            );

            httpClientBuilder
                    .setDefaultCredentialsProvider(credentialsProvider);

        }
    }

    RequestConfig defaultRequestConfig = RequestConfig
            .custom()
            .setCookieSpec(CookieSpecs.BEST_MATCH)
            .setExpectContinueEnabled(true)
            .setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(
                    Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
            .setConnectTimeout(config.getConnectionTimeout())
            .setSocketTimeout(config.getSocketTimeout())
            .setExpectContinueEnabled(config.isExceptContinue()).build();

    httpClientBuilder.setDefaultRequestConfig(defaultRequestConfig);
    httpClientBuilder
            .setMaxConnPerRoute(config.getMaxConnectionsPerRoute());
    httpClientBuilder.setMaxConnTotal(config.getMaxConnections());
    httpClientBuilder.setUserAgent(VersionInfoUtils.getDefaultUserAgent());
    CloseableHttpAsyncClient httpclient = httpClientBuilder.build();

    return httpclient;
}
 
Example #26
Source File: FDSHttpClient.java    From galaxy-fds-sdk-java with Apache License 2.0 4 votes vote down vote up
private HttpClient createHttpClient(FDSClientConfiguration config) {
  RequestConfig.Builder requestConfigBuilder = RequestConfig.custom()
      .setConnectTimeout(config.getConnectionTimeoutMs())
      .setSocketTimeout(config.getSocketTimeoutMs());

  String proxyHost = config.getProxyHost();

  int proxyPort = config.getProxyPort();

  if (proxyHost != null && proxyPort > 0) {
    HttpHost proxy = new HttpHost(proxyHost, proxyPort);
    requestConfigBuilder.setProxy(proxy);

    String proxyUsername = config.getProxyUsername();
    String proxyPassword = config.getProxyPassword();
    String proxyDomain = config.getProxyDomain();
    String proxyWorkstation = config.getProxyWorkstation();
    if (proxyUsername != null && proxyPassword != null) {
      credentialsProvider = new BasicCredentialsProvider();

      credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
          new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));

      authCache = new BasicAuthCache();
      authCache.put(proxy, new BasicScheme());
    }
  }

  RequestConfig requestConfig = requestConfigBuilder.build();

  SocketConfig socketConfig = SocketConfig.custom()
      .setSoTimeout(config.getSocketTimeoutMs())
      .build();

  RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
  registryBuilder.register("http", new ConnectionInfoRecorderSocketFactory(
      new PlainConnectionSocketFactory()));

  if (config.isHttpsEnabled()) {
    SSLContext sslContext = SSLContexts.createSystemDefault();
    SSLConnectionSocketFactory sslConnectionSocketFactory =
        new SSLConnectionInfoRecorderSocketFactory(
        sslContext,
        NoopHostnameVerifier.INSTANCE);
    registryBuilder.register("https", sslConnectionSocketFactory);
  }
  ipBlackList = new TimeBasedIpAddressBlackList(config.getIpAddressNegativeDurationMillsec());
  connectionManager = new PoolingHttpClientConnectionManager(registryBuilder.build(),
      null,
      null,
      new RoundRobinDNSResolver(new InternalSiteBlackListDNSResolver(ipBlackList,
          this.dnsResolver == null ?
              SystemDefaultDnsResolver.INSTANCE : this.dnsResolver)),
      config.getHTTPKeepAliveTimeoutMS(), TimeUnit.MILLISECONDS);
  connectionManager.setDefaultMaxPerRoute(config.getMaxConnection());
  connectionManager.setMaxTotal(config.getMaxConnection());
  connectionManager.setDefaultSocketConfig(socketConfig);
  FDSBlackListEnabledHostChecker fdsBlackListEnabledHostChecker =
      new FDSBlackListEnabledHostChecker();
  retryHandler = new InternalIpBlackListRetryHandler(config.getRetryCount(),
      ipBlackList, fdsBlackListEnabledHostChecker);

  return HttpClients.custom()
      .setRetryHandler(retryHandler)
      .setServiceUnavailableRetryStrategy(new ServiceUnavailableDNSBlackListStrategy(
          config.getRetryCount(),
          config.getRetryIntervalMilliSec(),
          ipBlackList,
          fdsBlackListEnabledHostChecker))
      .setConnectionManager(connectionManager)
      .setDefaultRequestConfig(requestConfig)
      .build();
}
 
Example #27
Source File: HttpClientWebRequest.java    From ews-java-api with MIT License 4 votes vote down vote up
/**
 * Prepares the request by setting appropriate headers, authentication, timeouts, etc.
 */
@Override
public void prepareConnection() {
  httpPost = new HttpPost(getUrl().toString());

  // Populate headers.
  httpPost.addHeader("Content-type", getContentType());
  httpPost.addHeader("User-Agent", getUserAgent());
  httpPost.addHeader("Accept", getAccept());
  httpPost.addHeader("Keep-Alive", "300");
  httpPost.addHeader("Connection", "Keep-Alive");

  if (isAcceptGzipEncoding()) {
    httpPost.addHeader("Accept-Encoding", "gzip,deflate");
  }

  if (getHeaders() != null) {
    for (Map.Entry<String, String> httpHeader : getHeaders().entrySet()) {
      httpPost.addHeader(httpHeader.getKey(), httpHeader.getValue());
    }
  }

  // Build request configuration.
  // Disable Kerberos in the preferred auth schemes - EWS should usually allow NTLM or Basic auth
  RequestConfig.Builder
      requestConfigBuilder =
      RequestConfig.custom().setAuthenticationEnabled(true).setConnectionRequestTimeout(getTimeout())
          .setConnectTimeout(getTimeout()).setRedirectsEnabled(isAllowAutoRedirect())
          .setSocketTimeout(getTimeout())
          .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.BASIC))
          .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.BASIC));

  CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

  // Add proxy credential if necessary.
  WebProxy proxy = getProxy();
  if (proxy != null) {
    HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort());
    requestConfigBuilder.setProxy(proxyHost);

    if (proxy.hasCredentials()) {
      NTCredentials
          proxyCredentials =
          new NTCredentials(proxy.getCredentials().getUsername(), proxy.getCredentials().getPassword(), "",
                            proxy.getCredentials().getDomain());

      credentialsProvider.setCredentials(new AuthScope(proxyHost), proxyCredentials);
    }
  }

  // Add web service credential if necessary.
  if (isAllowAuthentication() && getUsername() != null) {
    NTCredentials webServiceCredentials = new NTCredentials(getUsername(), getPassword(), "", getDomain());
    credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY), webServiceCredentials);
  }

  httpContext.setCredentialsProvider(credentialsProvider);

  httpPost.setConfig(requestConfigBuilder.build());
}
 
Example #28
Source File: RuntimeHttpUtils.java    From ibm-cos-sdk-java with Apache License 2.0 4 votes vote down vote up
/**
 * Fetches a file from the URI given and returns an input stream to it.
 *
 * @param uri the uri of the file to fetch
 * @param config optional configuration overrides
 * @return an InputStream containing the retrieved data
 * @throws IOException on error
 */
@SuppressWarnings("deprecation")
public static InputStream fetchFile(
        final URI uri,
        final ClientConfiguration config) throws IOException {

    HttpParams httpClientParams = new BasicHttpParams();
    HttpProtocolParams.setUserAgent(
            httpClientParams, getUserAgent(config, null));

    HttpConnectionParams.setConnectionTimeout(
            httpClientParams, getConnectionTimeout(config));
    HttpConnectionParams.setSoTimeout(
            httpClientParams, getSocketTimeout(config));

    DefaultHttpClient httpclient = new DefaultHttpClient(httpClientParams);

    if (config != null) {
        String proxyHost = config.getProxyHost();
        int proxyPort = config.getProxyPort();

        if (proxyHost != null && proxyPort > 0) {

            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            httpclient.getParams().setParameter(
                    ConnRoutePNames.DEFAULT_PROXY, proxy);

            if (config.getProxyUsername() != null
                && config.getProxyPassword() != null) {

                httpclient.getCredentialsProvider().setCredentials(
                        new AuthScope(proxyHost, proxyPort),
                        new NTCredentials(config.getProxyUsername(),
                                          config.getProxyPassword(),
                                          config.getProxyWorkstation(),
                                          config.getProxyDomain()));
            }
        }
    }

    HttpResponse response = httpclient.execute(new HttpGet(uri));

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new IOException("Error fetching file from " + uri + ": "
                              + response);
    }

    return new HttpClientWrappingInputStream(
            httpclient,
            response.getEntity().getContent());
}
 
Example #29
Source File: HttpFactory.java    From mq-http-java-sdk with MIT License 4 votes vote down vote up
public static CloseableHttpAsyncClient createHttpAsyncClient(
        PoolingNHttpClientConnectionManager connManager,
        ClientConfiguration config) {
    HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom()
            .setConnectionManager(connManager);

    // Set proxy if set.
    String proxyHost = config.getProxyHost();
    int proxyPort = config.getProxyPort();

    if (proxyHost != null && proxyPort > 0) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);

        httpClientBuilder.setProxy(proxy);

        String proxyUsername = config.getProxyUsername();
        String proxyPassword = config.getProxyPassword();

        if (proxyUsername != null && proxyPassword != null) {
            String proxyDomain = config.getProxyDomain();
            String proxyWorkstation = config.getProxyWorkstation();

            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

            credentialsProvider.setCredentials(new AuthScope(proxy),
                    new NTCredentials(proxyUsername, proxyPassword,
                            proxyWorkstation, proxyDomain)
            );

            httpClientBuilder
                    .setDefaultCredentialsProvider(credentialsProvider);

        }
    }

    RequestConfig defaultRequestConfig = RequestConfig
            .custom()
            .setCookieSpec(CookieSpecs.BEST_MATCH)
            .setExpectContinueEnabled(true)
            .setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(
                    Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
            .setConnectTimeout(config.getConnectionTimeout())
            .setSocketTimeout(config.getSocketTimeout())
            .setExpectContinueEnabled(config.isExceptContinue()).build();

    httpClientBuilder.setDefaultRequestConfig(defaultRequestConfig);
    httpClientBuilder
            .setMaxConnPerRoute(config.getMaxConnectionsPerRoute());
    httpClientBuilder.setMaxConnTotal(config.getMaxConnections());
    httpClientBuilder.setUserAgent(VersionInfoUtils.getDefaultUserAgent());
    CloseableHttpAsyncClient httpclient = httpClientBuilder.build();

    return httpclient;
}
 
Example #30
Source File: ProxyClientConfig.java    From gitlab4j-api with MIT License 3 votes vote down vote up
/**
 * Create a Map instance set up to use an NTLM proxy server that can be passed to the GitLabAPi constructors 
 * and login methods to configure the GitLabApi instance to use an NTLM proxy server.
 *
 * @param proxyUri the URI of the proxy server
 * @param username the user name. This should not include the domain to authenticate with.
 * For example: "user" is correct whereas "DOMAIN&#92;user" is not.
 * @param password the password
 * @param workstation the workstation the authentication request is originating from. Essentially, the computer name for this machine.
 * @param domain the domain to authenticate within
 * @return a Map set up to allow GitLabApi to use an NTLM proxy server
 */
public static Map<String, Object> createNtlmProxyClientConfig(String proxyUri, String username, String password, String workstation, String domain) {

    Map<String, Object> clientConfig = new HashMap<>();
    clientConfig.put(ClientProperties.PROXY_URI, proxyUri);

    CredentialsProvider credentials = new BasicCredentialsProvider();
    credentials.setCredentials(AuthScope.ANY, new NTCredentials(username, password, workstation, domain));
    clientConfig.put(ApacheClientProperties.CREDENTIALS_PROVIDER, credentials);

    return (clientConfig);
}