org.apache.http.auth.UsernamePasswordCredentials Java Examples

The following examples show how to use org.apache.http.auth.UsernamePasswordCredentials. 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: NexusArtifactClient.java    From cubeai with Apache License 2.0 8 votes vote down vote up
public boolean deleteArtifact(String longUrl) {
    try {
        CloseableHttpClient httpClient;
        if (getUserName() != null && getPassword() != null) {
            URL url = new URL(getUrl());
            HttpHost httpHost = new HttpHost(url.getHost(), url.getPort());
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(httpHost),
                new UsernamePasswordCredentials(getUserName(), getPassword()));
            httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build();
        } else {
            httpClient = HttpClientBuilder.create().build();
        }
        RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
        restTemplate.delete(new URI(longUrl));
    } catch (Exception e) {
        return false;
    }
    return true;
}
 
Example #2
Source File: ElasticsearchRestClientInstrumentationIT.java    From apm-agent-java with Apache License 2.0 8 votes vote down vote up
@BeforeClass
public static void startElasticsearchContainerAndClient() throws IOException {
    container = new ElasticsearchContainer(ELASTICSEARCH_CONTAINER_VERSION);
    container.start();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USER_NAME, PASSWORD));

    RestClientBuilder builder = RestClient.builder(HttpHost.create(container.getHttpHostAddress()))
        .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));

    client = new RestHighLevelClient(builder);

    client.indices().create(new CreateIndexRequest(INDEX), RequestOptions.DEFAULT);
    reporter.reset();
}
 
Example #3
Source File: KeycloakSmsAuthenticator.java    From keycloak-sms-authenticator with Eclipse Public License 2.0 6 votes vote down vote up
private CredentialsProvider getCredentialsProvider(String smsUsr, String smsPwd, String proxyUsr, String proxyPwd, URL smsURL, URL proxyURL) {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();

    // If defined, add BASIC Authentication parameters
    if (isNotEmpty(smsUsr) && isNotEmpty(smsPwd)) {
        credsProvider.setCredentials(
                new AuthScope(smsURL.getHost(), smsURL.getPort()),
                new UsernamePasswordCredentials(smsUsr, smsPwd));

    }

    // If defined, add Proxy Authentication parameters
    if (isNotEmpty(proxyUsr) && isNotEmpty(proxyPwd)) {
        credsProvider.setCredentials(
                new AuthScope(proxyURL.getHost(), proxyURL.getPort()),
                new UsernamePasswordCredentials(proxyUsr, proxyPwd));

    }
    return credsProvider;
}
 
Example #4
Source File: EsRestClientContainer.java    From frostmourne with MIT License 6 votes vote down vote up
public void init() {
    RestClientBuilder restClientBuilder = RestClient.builder(parseHttpHost(esHosts)
            .toArray(new HttpHost[0]));

    if (this.settings != null && this.settings.size() > 0 &&
            !Strings.isNullOrEmpty(this.settings.get("username"))
            && !Strings.isNullOrEmpty(this.settings.get("password"))) {
        String userName = this.settings.get("username");
        String password = this.settings.get("password");
        final CredentialsProvider credentialsProvider =
                new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(userName, password));
        restClientBuilder.setHttpClientConfigCallback(httpAsyncClientBuilder -> {
            httpAsyncClientBuilder.disableAuthCaching();
            return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        });
    }
    restHighLevelClient = new RestHighLevelClient(restClientBuilder);
    this.restLowLevelClient = restHighLevelClient.getLowLevelClient();
    if (sniff) {
        sniffer = Sniffer.builder(restLowLevelClient).setSniffIntervalMillis(5 * 60 * 1000).build();
    }
}
 
Example #5
Source File: RestAutoConfigure.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
/**
 * 异步httpclient连接数配置
 */
private void setHttpClientConfig(RestClientBuilder builder, RestClientPoolProperties poolProperties, RestClientProperties restProperties){
    builder.setHttpClientConfigCallback(httpClientBuilder -> {
        httpClientBuilder.setMaxConnTotal(poolProperties.getMaxConnectNum())
                .setMaxConnPerRoute(poolProperties.getMaxConnectPerRoute());

        PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull();
        map.from(restProperties::getUsername).to(username -> {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(username, restProperties.getPassword()));
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        });
        return httpClientBuilder;
    });
}
 
Example #6
Source File: ElasticsearchCollector.java    From Quicksql with MIT License 6 votes vote down vote up
private static RestClient connect(Map<String, Integer> coordinates,
    Map<String, String> userConfig) {
    Objects.requireNonNull(coordinates, "coordinates");
    Preconditions.checkArgument(! coordinates.isEmpty(), "no ES coordinates specified");
    final Set<HttpHost> set = new LinkedHashSet<>();
    for (Map.Entry<String, Integer> entry : coordinates.entrySet()) {
        set.add(new HttpHost(entry.getKey(), entry.getValue()));
    }

    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY,
        new UsernamePasswordCredentials(userConfig.getOrDefault("esUser", "none"),
            userConfig.getOrDefault("esPass", "none")));

    return RestClient.builder(set.toArray(new HttpHost[0]))
        .setHttpClientConfigCallback(httpClientBuilder ->
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider))
        .setMaxRetryTimeoutMillis(300000).build();
}
 
Example #7
Source File: ElasticsearchCustomSchemaFactory.java    From Quicksql with MIT License 6 votes vote down vote up
/**
 * Builds elastic rest client from user configuration
 *
 * @param coordinates list of {@code hostname/port} to connect to
 * @return newly initialized low-level rest http client for ES
 */
private static RestClient connect(Map<String, Integer> coordinates,
    Map<String, String> userConfig) {
    Objects.requireNonNull(coordinates, "coordinates");
    Preconditions.checkArgument(!coordinates.isEmpty(), "no ES coordinates specified");
    final Set<HttpHost> set = new LinkedHashSet<>();
    for (Map.Entry<String, Integer> entry : coordinates.entrySet()) {
        set.add(new HttpHost(entry.getKey(), entry.getValue()));
    }

    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY,
        new UsernamePasswordCredentials(userConfig.getOrDefault("esUser", "none"),
            userConfig.getOrDefault("esPass", "none")));

    return RestClient.builder(set.toArray(new HttpHost[0]))
        .setHttpClientConfigCallback(httpClientBuilder ->
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider))
        .setMaxRetryTimeoutMillis(300000).build();
}
 
Example #8
Source File: HopServer.java    From hop with Apache License 2.0 6 votes vote down vote up
private void addCredentials( HttpClientContext context ) {

    String host = environmentSubstitute( hostname );
    int port = Const.toInt( environmentSubstitute( this.port ), 80 );
    String userName = environmentSubstitute( username );
    String password = Encr.decryptPasswordOptionallyEncrypted( environmentSubstitute( this.password ) );
    String proxyHost = environmentSubstitute( proxyHostname );

    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials( userName, password );
    if ( !Utils.isEmpty( proxyHost ) && host.equals( "localhost" ) ) {
      host = "127.0.0.1";
    }
    provider.setCredentials( new AuthScope( host, port ), credentials );
    context.setCredentialsProvider( provider );
    // Generate BASIC scheme object and add it to the local auth cache
    HttpHost target = new HttpHost( host, port, isSslMode() ? HTTPS : HTTP );
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put( target, basicAuth );
    context.setAuthCache( authCache );
  }
 
Example #9
Source File: CMODataAbapClient.java    From devops-cm-client with Apache License 2.0 6 votes vote down vote up
public CMODataAbapClient(String endpoint, String user, String password) throws URISyntaxException {

        this.endpoint = new URI(endpoint);
        this.requestBuilder = new TransportRequestBuilder(this.endpoint);

        // the same instance needs to be used as long as we are in the same session. Hence multiple
        // clients must share the same cookie store. Reason: we are logged on with the first request
        // and get a cookie. That cookie - expressing the user has already been logged in - needs to be
        // present in all subsequent requests.
        CookieStore sessionCookieStore = new BasicCookieStore();

        BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
        basicCredentialsProvider.setCredentials(
                new AuthScope(this.endpoint.getHost(), this.endpoint.getPort()),
                new UsernamePasswordCredentials(user, password));

        this.clientFactory = new HttpClientFactory(sessionCookieStore, basicCredentialsProvider);
    }
 
Example #10
Source File: ServerConnectionManager.java    From hop with Apache License 2.0 6 votes vote down vote up
public HttpClient createHttpClient( String user, String password,
                                    String proxyHost, int proxyPort, AuthScope authScope ) {
  HttpHost httpHost = new HttpHost( proxyHost, proxyPort );

  RequestConfig requestConfig = RequestConfig.custom()
    .setProxy( httpHost )
    .build();

  CredentialsProvider provider = new BasicCredentialsProvider();
  UsernamePasswordCredentials credentials = new UsernamePasswordCredentials( user, password );
  provider.setCredentials( authScope, credentials );

  return
    HttpClientBuilder
      .create()
      .setDefaultCredentialsProvider( provider )
      .setDefaultRequestConfig( requestConfig )
      .setConnectionManager( manager )
      .build();
}
 
Example #11
Source File: ElasticsearchConfig.java    From staccato with Apache License 2.0 6 votes vote down vote up
/**
 * Registers an instance of the high level client for Elasticsearch.
 *
 * @return An instance of Elasticsearch's high level rest client
 */
@Bean
public RestHighLevelClient restHighLevelClient() {
    RestClientBuilder builder = RestClient.builder(new HttpHost(configProps.getHost(), configProps.getPort(), configProps.getScheme()));
    RestClientBuilder.HttpClientConfigCallback httpClientConfigCallback = httpAsyncClientBuilder -> {
        httpAsyncClientBuilder
                .setMaxConnTotal(configProps.getRestClientMaxConnectionsTotal())
                .setMaxConnPerRoute(configProps.getRestClientMaxConnectionsPerRoute());

        if (null != configProps.getUser() && !configProps.getUser().isEmpty()) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(configProps.getUser(), configProps.getPassword()));
            httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }

        return httpAsyncClientBuilder;
    };

    builder.setHttpClientConfigCallback(httpClientConfigCallback);
    builder.setMaxRetryTimeoutMillis(configProps.getRestClientMaxRetryTimeoutMillis());

    //return new RestHighLevelClient(builder.build());
    return new RestHighLevelClient(builder);
}
 
Example #12
Source File: NexusArtifactClient.java    From cubeai with Apache License 2.0 6 votes vote down vote up
public boolean deleteArtifact(String longUrl) {
    try {
        CloseableHttpClient httpClient;
        if (getUserName() != null && getPassword() != null) {
            URL url = new URL(getUrl());
            HttpHost httpHost = new HttpHost(url.getHost(), url.getPort());
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(httpHost),
                new UsernamePasswordCredentials(getUserName(), getPassword()));
            httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build();
        } else {
            httpClient = HttpClientBuilder.create().build();
        }
        RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
        restTemplate.delete(new URI(longUrl));
    } catch (Exception e) {
        return false;
    }
    return true;
}
 
Example #13
Source File: NexusArtifactClient.java    From cubeai with Apache License 2.0 6 votes vote down vote up
public boolean deleteArtifact(String longUrl) {
    try {
        CloseableHttpClient httpClient;
        if (getUserName() != null && getPassword() != null) {
            URL url = new URL(getUrl());
            HttpHost httpHost = new HttpHost(url.getHost(), url.getPort());
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(httpHost),
                new UsernamePasswordCredentials(getUserName(), getPassword()));
            httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build();
        } else {
            httpClient = HttpClientBuilder.create().build();
        }
        RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
        restTemplate.delete(new URI(longUrl));
    } catch (Exception e) {
        return false;
    }
    return true;
}
 
Example #14
Source File: NexusArtifactClient.java    From cubeai with Apache License 2.0 6 votes vote down vote up
public boolean deleteArtifact(String longUrl) {
    try {
        CloseableHttpClient httpClient;
        if (getUserName() != null && getPassword() != null) {
            URL url = new URL(getUrl());
            HttpHost httpHost = new HttpHost(url.getHost(), url.getPort());
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(httpHost),
                new UsernamePasswordCredentials(getUserName(), getPassword()));
            httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build();
        } else {
            httpClient = HttpClientBuilder.create().build();
        }
        RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
        restTemplate.delete(new URI(longUrl));
    } catch (Exception e) {
        return false;
    }
    return true;
}
 
Example #15
Source File: NotificationUtil.java    From qy-wechat-notification-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * 推送信息
 * @param url
 * @param data
 */
public static String push(String url, String data, NotificationConfig buildConfig) throws HttpProcessException {
    HttpConfig httpConfig;
    //使用代理请求
    if(buildConfig.useProxy){
        HttpClient httpClient;
        HttpHost proxy = new HttpHost(buildConfig.proxyHost, buildConfig.proxyPort);
        //用户密码
        if(StringUtils.isNotEmpty(buildConfig.proxyUsername) && buildConfig.proxyPassword != null){
            // 设置认证
            CredentialsProvider provider = new BasicCredentialsProvider();
            provider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(buildConfig.proxyUsername, Secret.toString(buildConfig.proxyPassword)));
            httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).setProxy(proxy).build();
        }else{
            httpClient = HttpClients.custom().setProxy(proxy).build();
        }
        //代理请求
        httpConfig = HttpConfig.custom().client(httpClient).url(url).json(data).encoding("utf-8");
    }else{
        //普通请求
        httpConfig = HttpConfig.custom().url(url).json(data).encoding("utf-8");
    }

    String result = HttpClientUtil.post(httpConfig);
    return result;
}
 
Example #16
Source File: WxPayServiceApacheHttpImpl.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
private HttpClientBuilder createHttpClientBuilder(boolean useKey) throws WxPayException {
  HttpClientBuilder httpClientBuilder = HttpClients.custom();
  if (useKey) {
    this.initSSLContext(httpClientBuilder);
  }

  if (StringUtils.isNotBlank(this.getConfig().getHttpProxyHost())
    && this.getConfig().getHttpProxyPort() > 0) {
    // 使用代理服务器 需要用户认证的代理服务器
    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(
      new AuthScope(this.getConfig().getHttpProxyHost(), this.getConfig().getHttpProxyPort()),
      new UsernamePasswordCredentials(this.getConfig().getHttpProxyUsername(), this.getConfig().getHttpProxyPassword()));
    httpClientBuilder.setDefaultCredentialsProvider(provider);
  }
  return httpClientBuilder;
}
 
Example #17
Source File: ElasticsearchRestClientInstrumentationIT.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void startElasticsearchContainerAndClient() throws IOException {
    // Start the container
    container = new ElasticsearchContainer(ELASTICSEARCH_CONTAINER_VERSION);
    container.start();

    // Create the client
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USER_NAME, PASSWORD));

    RestClientBuilder builder = RestClient.builder(HttpHost.create(container.getHttpHostAddress()))
        .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
    client = new RestHighLevelClient(builder);

    client.indices().create(new CreateIndexRequest(INDEX), RequestOptions.DEFAULT);
    reporter.reset();
}
 
Example #18
Source File: ElasticsearchRestClientInstrumentationIT.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void startElasticsearchContainerAndClient() throws IOException {
    // Start the container
    container = new ElasticsearchContainer(ELASTICSEARCH_CONTAINER_VERSION);
    container.start();

    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USER_NAME, PASSWORD));

    RestClientBuilder builder =  RestClient.builder(HttpHost.create(container.getHttpHostAddress()))
        .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
    lowLevelClient = builder.build();
    client = new RestHighLevelClient(lowLevelClient);

    lowLevelClient.performRequest("PUT", "/" + INDEX);
    reporter.reset();
}
 
Example #19
Source File: ElasticConnection.java    From kafka-connect-elasticsearch-source with Apache License 2.0 6 votes vote down vote up
public ElasticConnection(String host, int port, String user, String pwd,
                         int maxConnectionAttempts, long connectionRetryBackoff) {

    logger.info("elastic auth enabled");

    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(user, pwd));

    //TODO add configuration for https also, and many nodes instead of only one
    client = new RestHighLevelClient(
            RestClient.builder(
                    new HttpHost(host, port)).setHttpClientConfigCallback(
                    httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
            )
    );

    this.maxConnectionAttempts = maxConnectionAttempts;
    this.connectionRetryBackoff = connectionRetryBackoff;

}
 
Example #20
Source File: AxivionSuite.java    From warnings-ng-plugin with MIT License 6 votes vote down vote up
private UsernamePasswordCredentials withValidCredentials() {
    final List<StandardUsernamePasswordCredentials> all =
            CredentialsProvider.lookupCredentials(
                    StandardUsernamePasswordCredentials.class,
                    (Item) null,
                    ACL.SYSTEM,
                    Collections.emptyList());

    StandardUsernamePasswordCredentials jenkinsCredentials =
            CredentialsMatchers.firstOrNull(all,
                    CredentialsMatchers.withId(credentialsId));

    if (jenkinsCredentials == null) {
        throw new ParsingException("Could not find the credentials for " + credentialsId);
    }

    return new UsernamePasswordCredentials(
            jenkinsCredentials.getUsername(),
            Secret.toString(jenkinsCredentials.getPassword()));
}
 
Example #21
Source File: EsMediaSourceController.java    From DataLink with Apache License 2.0 6 votes vote down vote up
private void verify(String url, String user, String pass) {
    try {
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, pass);
        provider.setCredentials(AuthScope.ANY, credentials);
        HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
        HttpResponse response = client.execute(new HttpGet(url));
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new ValidationException("verify elasticsearch node [" + url + "] failure, response status: " + response);
        }

        logger.info("Verify Es MediaSource successfully.");
    } catch (Exception e) {
        throw new ValidationException("verify elasticsearch node [" + url + "] failure, cause of: " + e);
    }
}
 
Example #22
Source File: ElasticsearchAuditLogSink.java    From Groza with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void init() {
    try {
        log.trace("Adding elastic rest endpoint... host [{}], port [{}], scheme name [{}]",
                host, port, schemeName);
        RestClientBuilder builder = RestClient.builder(
                new HttpHost(host, port, schemeName));

        if (StringUtils.isNotEmpty(userName) &&
                StringUtils.isNotEmpty(password)) {
            log.trace("...using username [{}] and password ***", userName);
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(userName, password));
            builder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
        }

        this.restClient = builder.build();
    } catch (Exception e) {
        log.error("Sink init failed!", e);
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example #23
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 #24
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 #25
Source File: UrlAuthenticatorDialog.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * constructor
 *
 * @param parent JFrame
 */
public UrlAuthenticatorDialog(javax.swing.JFrame parent) {
  PrefPanel pp = new PrefPanel("UrlAuthenticatorDialog", null);
  serverF = pp.addTextField("server", "Server", "wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww");
  realmF = pp.addTextField("realm", "Realm", "");
  serverF.setEditable(false);
  realmF.setEditable(false);

  userF = pp.addTextField("user", "User", "");
  passwF = pp.addPasswordField("password", "Password", "");
  pp.addActionListener(e -> {
    char[] pw = passwF.getPassword();
    if (pw == null)
      return;
    pwa = new UsernamePasswordCredentials(userF.getText(), new String(pw));
    dialog.setVisible(false);
  });
  // button to dismiss
  JButton cancel = new JButton("Cancel");
  pp.addButton(cancel);
  cancel.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
      pwa = null;
      dialog.setVisible(false);
    }
  });
  pp.finish();

  dialog = new IndependentDialog(parent, true, "HTTP Authentication", pp);
  dialog.setLocationRelativeTo(parent);
  dialog.setLocation(100, 100);
}
 
Example #26
Source File: UrlAuthenticatorDialog.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public Credentials getCredentials(AuthScope scope) {
  // Search dialogcache first
  Credentials creds = null;
  AuthScope bestMatch = null;
  bestMatch = HTTPAuthUtil.bestmatch(scope, dialogcache.keySet());
  if (bestMatch != null) {
    creds = dialogcache.get(bestMatch);
  }
  if (creds == null) {
    // try the set cache
    bestMatch = HTTPAuthUtil.bestmatch(scope, setcache.keySet());
    if (bestMatch != null) {
      creds = setcache.get(bestMatch);
    }
  }
  if (creds != null)
    return creds;
  // No cached creds, so ask user
  serverF.setText(scope.getHost() + ":" + scope.getPort());
  realmF.setText(scope.getRealm());
  dialog.setVisible(true);
  if (pwa == null)
    throw new IllegalStateException();
  if (debug) {
    System.out.println("user= (" + pwa.getUserName() + ")");
    System.out.println("password= (" + pwa.getPassword() + ")");
  }
  // Is this really necessary?
  UsernamePasswordCredentials upc = new UsernamePasswordCredentials(pwa.getUserName(), pwa.getPassword());
  dialogcache.put(scope, upc);
  return upc;
}
 
Example #27
Source File: ElasticsearchAutoConfiguration.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * get restHistLevelClient
 *
 * @param builder                 RestClientBuilder
 * @param elasticsearchProperties elasticsearch default properties
 * @return {@link org.elasticsearch.client.RestHighLevelClient}
 * @author fxbin
 */
private static RestHighLevelClient getRestHighLevelClient(RestClientBuilder builder, ElasticsearchProperties elasticsearchProperties) {

    // Callback used the default {@link RequestConfig} being set to the {@link CloseableHttpClient}
    builder.setRequestConfigCallback(requestConfigBuilder -> {
        requestConfigBuilder.setConnectTimeout(elasticsearchProperties.getConnectTimeout());
        requestConfigBuilder.setSocketTimeout(elasticsearchProperties.getSocketTimeout());
        requestConfigBuilder.setConnectionRequestTimeout(elasticsearchProperties.getConnectionRequestTimeout());
        return requestConfigBuilder;
    });

    // Callback used to customize the {@link CloseableHttpClient} instance used by a {@link RestClient} instance.
    builder.setHttpClientConfigCallback(httpClientBuilder -> {
        httpClientBuilder.setMaxConnTotal(elasticsearchProperties.getMaxConnectTotal());
        httpClientBuilder.setMaxConnPerRoute(elasticsearchProperties.getMaxConnectPerRoute());
        return httpClientBuilder;
    });

    // Callback used the basic credential auth
    ElasticsearchProperties.Account account = elasticsearchProperties.getAccount();
    if (!StringUtils.isEmpty(account.getUsername()) && !StringUtils.isEmpty(account.getUsername())) {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(account.getUsername(), account.getPassword()));
    }
    return new RestHighLevelClient(builder);
}
 
Example #28
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 #29
Source File: AwsRestHighLevelClient.java    From aws-athena-query-federation with Apache License 2.0 5 votes vote down vote up
/**
 * Injects the client builder with username/password credentials.
 * @param username is the username used for the domain.
 * @param password is the password used for the domain.
 * @return self.
 */
public Builder withCredentials(String username, String password)
{
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(username, password));

    clientBuilder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
            .setDefaultCredentialsProvider(credentialsProvider));

    return this;
}
 
Example #30
Source File: HtmlUnitRequestBuilderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void buildRequestBasicAuth() {
	String base64Credentials = "dXNlcm5hbWU6cGFzc3dvcmQ=";
	String authzHeaderValue = "Basic: " + base64Credentials;
	UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(base64Credentials);
	webRequest.setCredentials(credentials);
	webRequest.setAdditionalHeader("Authorization", authzHeaderValue);

	MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);

	assertThat(actualRequest.getAuthType(), equalTo("Basic"));
	assertThat(actualRequest.getHeader("Authorization"), equalTo(authzHeaderValue));
}