org.apache.http.client.CredentialsProvider Java Examples
The following examples show how to use
org.apache.http.client.CredentialsProvider.
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 |
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: GeoServerIT.java From geowave with Apache License 2.0 | 6 votes |
protected static Pair<CloseableHttpClient, HttpClientContext> createClientAndContext() { final CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials( new AuthScope("localhost", ServicesTestEnvironment.JETTY_PORT), new UsernamePasswordCredentials( ServicesTestEnvironment.GEOSERVER_USER, ServicesTestEnvironment.GEOSERVER_PASS)); final AuthCache authCache = new BasicAuthCache(); final HttpHost targetHost = new HttpHost("localhost", ServicesTestEnvironment.JETTY_PORT, "http"); authCache.put(targetHost, new BasicScheme()); // Add AuthCache to the execution context final HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(provider); context.setAuthCache(authCache); return ImmutablePair.of( HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build(), context); }
Example #3
Source File: SslTrustCorporateProxyHttpClient.java From zerocode with Apache License 2.0 | 6 votes |
@Override public CloseableHttpClient createHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException { LOGGER.info("###Used SSL Enabled Http Client with Corporate Proxy, for both Http and Https connections"); SSLContext sslContext = new SSLContextBuilder() .loadTrustMaterial(null, (certificate, authType) -> true).build(); CookieStore cookieStore = new BasicCookieStore(); CredentialsProvider credsProvider = createProxyCredentialsProvider(proxyHost, proxyPort, proxyUserName, proxyPassword); HttpHost proxy = new HttpHost(proxyHost, proxyPort); return HttpClients.custom() .setSSLContext(sslContext) .setSSLHostnameVerifier(new NoopHostnameVerifier()) .setDefaultCookieStore(cookieStore) .setDefaultCredentialsProvider(credsProvider) .setProxy(proxy) .build(); }
Example #4
Source File: ContextCredentialsConfigurationRegistrarTest.java From spring-cloud-aws with Apache License 2.0 | 6 votes |
@Test void credentialsProvider_configWithInstanceProfile_instanceProfileCredentialsProviderConfigured() throws Exception { // Arrange this.context = new AnnotationConfigApplicationContext( ApplicationConfigurationWithInstanceProfileOnly.class); // Act AWSCredentialsProvider awsCredentialsProvider = this.context .getBean(AWSCredentialsProvider.class); // Assert assertThat(awsCredentialsProvider).isNotNull(); @SuppressWarnings("unchecked") List<CredentialsProvider> credentialsProviders = (List<CredentialsProvider>) ReflectionTestUtils .getField(awsCredentialsProvider, "credentialsProviders"); assertThat(credentialsProviders.size()).isEqualTo(1); assertThat(EC2ContainerCredentialsProviderWrapper.class .isInstance(credentialsProviders.get(0))).isTrue(); }
Example #5
Source File: ApacheUtils.java From ibm-cos-sdk-java with Apache License 2.0 | 6 votes |
private static void addPreemptiveAuthenticationProxy(HttpClientContext clientContext, HttpClientSettings settings) { if (settings.isPreemptiveBasicProxyAuth()) { HttpHost targetHost = new HttpHost(settings.getProxyHost(), settings .getProxyPort()); final CredentialsProvider credsProvider = newProxyCredentialsProvider(settings); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); clientContext.setCredentialsProvider(credsProvider); clientContext.setAuthCache(authCache); } }
Example #6
Source File: ElasticsearchConnection.java From components with Apache License 2.0 | 6 votes |
public static RestClient createClient(ElasticsearchDatastoreProperties datastore) throws MalformedURLException { String urlStr = datastore.nodes.getValue(); String[] urls = urlStr.split(","); HttpHost[] hosts = new HttpHost[urls.length]; int i = 0; for (String address : urls) { URL url = new URL("http://" + address); hosts[i] = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); i++; } RestClientBuilder restClientBuilder = RestClient.builder(hosts); if (datastore.auth.useAuth.getValue()) { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(datastore.auth.userId.getValue(), datastore.auth.password.getValue())); restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() { public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) { return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } }); } return restClientBuilder.build(); }
Example #7
Source File: ElasticsearchAuditLogSink.java From Groza with Apache License 2.0 | 6 votes |
@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 #8
Source File: SlackNotificationImpl.java From tcSlackBuildNotifier with MIT License | 6 votes |
public void setProxy(String proxyHost, Integer proxyPort, Credentials credentials) { this.proxyHost = proxyHost; this.proxyPort = proxyPort; if (this.proxyHost.length() > 0 && !this.proxyPort.equals(0)) { HttpClientBuilder clientBuilder = HttpClients.custom() .useSystemProperties() .setProxy(new HttpHost(proxyHost, proxyPort, "http")); if (credentials != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), credentials); clientBuilder.setDefaultCredentialsProvider(credsProvider); Loggers.SERVER.debug("SlackNotification ::using proxy credentials " + credentials.getUserPrincipal().getName()); } this.client = clientBuilder.build(); } }
Example #9
Source File: ElasticsearchCollector.java From Quicksql with MIT License | 6 votes |
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 #10
Source File: HDInsightInstance.java From reef with Apache License 2.0 | 6 votes |
private HttpClientContext getClientContext(final String hostname, final String username, final String password) throws IOException { final HttpHost targetHost = new HttpHost(hostname, 443, "https"); final HttpClientContext result = HttpClientContext.create(); // Setup credentials provider final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); result.setCredentialsProvider(credentialsProvider); // Setup preemptive authentication final AuthCache authCache = new BasicAuthCache(); final BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); result.setAuthCache(authCache); final HttpGet httpget = new HttpGet("/"); // Prime the cache try (CloseableHttpResponse response = this.httpClient.execute(targetHost, httpget, result)) { // empty try block used to automatically close resources } return result; }
Example #11
Source File: ResolveSnapshotVersion.java From vertx-deploy-tools with Apache License 2.0 | 6 votes |
public Observable<T> executeAsync(T request) { CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(config.getHttpAuthUser(), config.getHttpAuthPassword()); provider.setCredentials(AuthScope.ANY, credentials); final URI location = config.getNexusUrl().resolve(config.getNexusUrl().getPath() + "/" + request.getMetadataLocation()); HttpUriRequest get = new HttpGet(location); Path filename = createTempFile(request.getArtifactId()); try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build(); CloseableHttpResponse response = client.execute(get)) { LOG.info("[{} - {}]: Downloaded Metadata for {}.", LogConstants.DEPLOY_ARTIFACT_REQUEST, request.getId(), request.getModuleId()); response.getEntity().writeTo(new FileOutputStream(filename.toFile())); request.setVersion(retrieveAndParseMetadata(filename, request)); } catch (IOException e) { LOG.error("[{} - {}]: Error downloading Metadata -> {}, {}", LogConstants.DEPLOY_ARTIFACT_REQUEST, request.getId(), e.getMessage(), e); throw new IllegalStateException(e); } return just(request); }
Example #12
Source File: HttpService.java From arcusplatform with Apache License 2.0 | 6 votes |
public static CloseableHttpResponse execute(HttpUriRequest req, @Nullable Credentials auth) throws IOException { if (auth != null) { URI uri = req.getURI(); AuthScope scope = new AuthScope(uri.getHost(), uri.getPort()); CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(scope, auth); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(provider); return get().execute(req, context); } return execute(req); }
Example #13
Source File: DigestAuthHandler.java From restfiddle with Apache License 2.0 | 6 votes |
public void setCredentialsProvider(RfRequestDTO requestDTO, HttpClientBuilder clientBuilder) { DigestAuthDTO digestAuthDTO = requestDTO.getDigestAuthDTO(); if (digestAuthDTO == null) { return; } String userName = digestAuthDTO.getUsername(); String password = digestAuthDTO.getPassword(); if (userName == null || userName.isEmpty() || password == null || password.isEmpty()) { return; } CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), new UsernamePasswordCredentials(userName, password)); clientBuilder.setDefaultCredentialsProvider(credentialsProvider); }
Example #14
Source File: SPARQLProtocolSession.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
protected void setUsernameAndPasswordForUrl(String username, String password, String url) { if (username != null && password != null) { logger.debug("Setting username '{}' and password for server at {}.", username, url); java.net.URI requestURI = java.net.URI.create(url); String host = requestURI.getHost(); int port = requestURI.getPort(); AuthScope scope = new AuthScope(host, port); UsernamePasswordCredentials cred = new UsernamePasswordCredentials(username, password); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(scope, cred); httpContext.setCredentialsProvider(credsProvider); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); HttpHost httpHost = new HttpHost(requestURI.getHost(), requestURI.getPort(), requestURI.getScheme()); authCache.put(httpHost, basicAuth); httpContext.setAuthCache(authCache); } else { httpContext.removeAttribute(HttpClientContext.AUTH_CACHE); httpContext.removeAttribute(HttpClientContext.CREDS_PROVIDER); } }
Example #15
Source File: HttpSender.java From cloudhopper-commons with Apache License 2.0 | 6 votes |
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); // If no auth scheme avaialble yet, try to initialize it preemptively if (authState.getAuthScheme() == null) { AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth"); CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (authScheme != null) { Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort())); if (creds == null) { throw new HttpException("No credentials for preemptive authentication"); } authState.setAuthScheme(authScheme); authState.setCredentials(creds); } } }
Example #16
Source File: ElasticsearchRestClientInstrumentationIT.java From apm-agent-java with Apache License 2.0 | 6 votes |
@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 #17
Source File: AbstractCheckThread.java From sitemonitoring-production with BSD 3-Clause "New" or "Revised" License | 6 votes |
protected CloseableHttpClient buildHttpClient() { HttpClientBuilder httpClientBuilder = HttpClients.custom(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); try { Credentials credentials = check.getCredentials(); if (credentials != null) { basicAuthentication(httpClientBuilder, credsProvider, credentials); } } catch (Exception ex) { throw new RuntimeException("Could not use credentials"); } // set proxy if (check.getHttpProxyUsername() != null && !check.getHttpProxyPassword().isEmpty()) { credsProvider.setCredentials(new AuthScope(check.getHttpProxyServer(), check.getHttpProxyPort()), new UsernamePasswordCredentials(check.getHttpProxyUsername(), check.getHttpProxyPassword())); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); } return httpClientBuilder.build(); }
Example #18
Source File: HttpClientConfigurer.java From pushfish-android with BSD 2-Clause "Simplified" License | 6 votes |
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); if (authState.getAuthScheme() != null || authState.hasAuthOptions()) { return; } // If no authState has been established and this is a PUT or POST request, add preemptive authorisation String requestMethod = request.getRequestLine().getMethod(); if (requestMethod.equals(HttpPut.METHOD_NAME) || requestMethod.equals(HttpPost.METHOD_NAME)) { CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); Credentials credentials = credentialsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort())); if (credentials == null) { throw new HttpException("No credentials for preemptive authentication"); } authState.update(authScheme, credentials); } }
Example #19
Source File: BasicCredentialsTest.java From log4j2-elasticsearch with Apache License 2.0 | 6 votes |
@Test public void objectIsConfiguredWhenAllParamsAreSet() { // given BasicCredentials BasicCredentials = createTestBuilder() .withUsername(TEST_USER) .withPassword(TEST_PASSWORD) .build(); HttpClientFactory.Builder settings = spy(createDefaultTestObjectBuilder()); // when BasicCredentials.applyTo(settings); // then verify(settings).withDefaultCredentialsProvider((CredentialsProvider) notNull()); }
Example #20
Source File: ElasticsearchClientFactory.java From metron with Apache License 2.0 | 6 votes |
private static CredentialsProvider getCredentialsProvider( ElasticsearchClientConfig esClientConfig) { Optional<Entry<String, String>> credentials = esClientConfig.getCredentials(); if (credentials.isPresent()) { LOG.info( "Found auth credentials - setting up user/pass authenticated client connection for ES."); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials upcredentials = new UsernamePasswordCredentials( credentials.get().getKey(), credentials.get().getValue()); credentialsProvider.setCredentials(AuthScope.ANY, upcredentials); return credentialsProvider; } else { LOG.info( "Elasticsearch client credentials not provided. Defaulting to non-authenticated client connection."); return null; } }
Example #21
Source File: AbstractCheckThread.java From sitemonitoring-production with BSD 3-Clause "New" or "Revised" License | 6 votes |
protected CloseableHttpClient buildHttpClient() { HttpClientBuilder httpClientBuilder = HttpClients.custom(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); try { Credentials credentials = check.getCredentials(); if (credentials != null) { basicAuthentication(httpClientBuilder, credsProvider, credentials); } } catch (Exception ex) { throw new RuntimeException("Could not use credentials"); } // set proxy if (check.getHttpProxyUsername() != null && !check.getHttpProxyPassword().isEmpty()) { credsProvider.setCredentials(new AuthScope(check.getHttpProxyServer(), check.getHttpProxyPort()), new UsernamePasswordCredentials(check.getHttpProxyUsername(), check.getHttpProxyPassword())); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); } return httpClientBuilder.build(); }
Example #22
Source File: AsyncClientAuthentication.java From yunpian-java-sdk with MIT License | 6 votes |
public static void main(String[] args) throws Exception { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope("localhost", 443), new UsernamePasswordCredentials("username", "password")); CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultCredentialsProvider(credsProvider) .build(); try { HttpGet httpget = new HttpGet("http://localhost/"); System.out.println("Executing request " + httpget.getRequestLine()); Future<HttpResponse> future = httpclient.execute(httpget, null); HttpResponse response = future.get(); System.out.println("Response: " + response.getStatusLine()); System.out.println("Shutting down"); } finally { httpclient.close(); } }
Example #23
Source File: ApiGatewayTest.java From Inside_Android_Testing with Apache License 2.0 | 5 votes |
@Test public void shouldMakeRemotePostCalls() throws Exception { Robolectric.getBackgroundScheduler().pause(); TestPostRequest apiRequest = new TestPostRequest(); apiGateway.makeRequest(apiRequest, responseCallbacks); Robolectric.addPendingHttpResponse(200, GENERIC_XML); Robolectric.getBackgroundScheduler().runOneTask(); HttpRequestInfo sentHttpRequestData = Robolectric.getSentHttpRequestInfo(0); HttpRequest sentHttpRequest = sentHttpRequestData.getHttpRequest(); assertThat(sentHttpRequest.getRequestLine().getUri(), equalTo("www.example.com")); assertThat(sentHttpRequest.getRequestLine().getMethod(), equalTo(HttpPost.METHOD_NAME)); assertThat(sentHttpRequest.getHeaders("foo")[0].getValue(), equalTo("bar")); InputStream contentStream = ((HttpPost) sentHttpRequest).getEntity().getContent(); assertThat(Strings.fromStream(contentStream), CoreMatchers.equalTo("post body content")); CredentialsProvider credentialsProvider = (CredentialsProvider) sentHttpRequestData.getHttpContext().getAttribute(ClientContext.CREDS_PROVIDER); assertThat(credentialsProvider.getCredentials(AuthScope.ANY).getUserPrincipal().getName(), CoreMatchers.equalTo("spongebob")); assertThat(credentialsProvider.getCredentials(AuthScope.ANY).getPassword(), CoreMatchers.equalTo("squarepants")); }
Example #24
Source File: ContextCredentialsConfigurationRegistrarTest.java From spring-cloud-aws with Apache License 2.0 | 5 votes |
@Test void credentialsProvider_configWithAccessAndSecretKeyAsExpressions_staticAwsCredentialsProviderConfiguredWithResolvedExpressions() throws Exception { // @checkstyle:on // Arrange this.context = new AnnotationConfigApplicationContext(); Map<String, Object> secretAndAccessKeyMap = new HashMap<>(); secretAndAccessKeyMap.put("accessKey", "accessTest"); secretAndAccessKeyMap.put("secretKey", "testSecret"); this.context.getEnvironment().getPropertySources() .addLast(new MapPropertySource("test", secretAndAccessKeyMap)); this.context.register( ApplicationConfigurationWithAccessKeyAndSecretKeyAsExpressions.class); this.context.refresh(); // Act AWSCredentialsProvider awsCredentialsProvider = this.context .getBean(AWSCredentialsProvider.class); // Assert assertThat(awsCredentialsProvider).isNotNull(); @SuppressWarnings("unchecked") List<CredentialsProvider> credentialsProviders = (List<CredentialsProvider>) ReflectionTestUtils .getField(awsCredentialsProvider, "credentialsProviders"); assertThat(credentialsProviders.size()).isEqualTo(1); assertThat(AWSStaticCredentialsProvider.class .isInstance(credentialsProviders.get(0))).isTrue(); assertThat(awsCredentialsProvider.getCredentials().getAWSAccessKeyId()) .isEqualTo("accessTest"); assertThat(awsCredentialsProvider.getCredentials().getAWSSecretKey()) .isEqualTo("testSecret"); }
Example #25
Source File: CredentialsProviderBuilderTest.java From cs-actions with Apache License 2.0 | 5 votes |
private CredentialsProvider getCredentialsProvider(String authType) { AuthTypes authTypes = new AuthTypes(authType); CredentialsProviderBuilder builder = new CredentialsProviderBuilder() .setAuthTypes(authTypes) .setUsername("DOMAIN\\username") .setPassword("pass") .setHost("host") .setPort("80") .setProxyHost("proxy") .setProxyPort("8080") .setProxyPassword("proxyPass") .setProxyUsername("proxyUsername"); return builder.buildCredentialsProvider(); }
Example #26
Source File: HttpClientConfigurator.java From bintray-client-java with Apache License 2.0 | 5 votes |
@Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { HttpClientContext clientContext = HttpClientContext.adapt(context); AuthState proxyAuthState = clientContext.getProxyAuthState(); // If there's no auth scheme available yet, try to initialize it preemptively if (proxyAuthState.getAuthScheme() == null) { CredentialsProvider credsProvider = clientContext.getCredentialsProvider(); RouteInfo route = clientContext.getHttpRoute(); if (route == null) { if (log.isDebugEnabled()) { log.debug("No route found for {}", clientContext.getTargetHost()); } return; } HttpHost proxyHost = route.getProxyHost(); if (proxyHost == null) { log.warn("No proxy host found in route {} for host {}", route, clientContext.getTargetHost()); return; } Credentials creds = credsProvider.getCredentials( new AuthScope(proxyHost.getHostName(), proxyHost.getPort())); if (creds == null) { log.info("No credentials found for proxy: " + proxyHost); return; } proxyAuthState.update(new BasicScheme(ChallengeState.PROXY), creds); } }
Example #27
Source File: HttpClientSandboxLiveTest.java From tutorials with MIT License | 5 votes |
@Test public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); final AuthScope authscp = new AuthScope("localhost", 8080); credentialsProvider.setCredentials(authscp, new UsernamePasswordCredentials("user1", "user1Pass")); final CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build(); final HttpGet httpGet = new HttpGet("http://localhost:8080/spring-security-rest-basic-auth/api/foos/1"); final CloseableHttpResponse response = client.execute(httpGet); System.out.println(response.getStatusLine()); ResponseUtil.closeResponse(response); }
Example #28
Source File: HttpClient.java From ats-framework with Apache License 2.0 | 5 votes |
/** * 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: HttpClientConfigurerTests.java From spring-cloud-dataflow with Apache License 2.0 | 5 votes |
/** * Test ensuring that the {@link AuthScope} is set for the target host. */ @Test public void testThatHttpClientWithProxyIsCreatedAndHasCorrectCredentialsProviders() throws Exception { final URI targetHost = new URI("http://test.com"); final HttpClientConfigurer builder = HttpClientConfigurer.create(targetHost); builder.basicAuthCredentials("foo", "password"); builder.withProxyCredentials(URI.create("https://spring.io"), null, null); final Field credentialsProviderField = ReflectionUtils.findField(HttpClientConfigurer.class, "credentialsProvider"); ReflectionUtils.makeAccessible(credentialsProviderField); CredentialsProvider credentialsProvider = (CredentialsProvider) credentialsProviderField.get(builder); Assert.assertNotNull(credentialsProvider.getCredentials(new AuthScope("test.com", 80))); Assert.assertNull(credentialsProvider.getCredentials(new AuthScope("spring.io", 80))); }
Example #30
Source File: SPARQLEndpointExecution.java From hypergraphql with Apache License 2.0 | 5 votes |
@Override public SPARQLExecutionResult call() { Map<String, Set<String>> resultSet = new HashMap<>(); markers.forEach(marker -> resultSet.put(marker, new HashSet<>())); Model unionModel = ModelFactory.createDefaultModel(); SPARQLServiceConverter converter = new SPARQLServiceConverter(schema); String sparqlQuery = converter.getSelectQuery(query, inputSubset, rootType); logger.info(sparqlQuery); CredentialsProvider credsProvider = new BasicCredentialsProvider(); Credentials credentials = new UsernamePasswordCredentials(this.sparqlEndpointService.getUser(), this.sparqlEndpointService.getPassword()); credsProvider.setCredentials(AuthScope.ANY, credentials); HttpClient httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credsProvider) .build(); HttpOp.setDefaultHttpClient(httpclient); Query jenaQuery = QueryFactory.create(sparqlQuery); QueryEngineHTTP qEngine = QueryExecutionFactory.createServiceRequest(this.sparqlEndpointService.getUrl(), jenaQuery); qEngine.setClient(httpclient); ResultSet results = qEngine.execSelect(); results.forEachRemaining(solution -> { markers.stream().filter(solution::contains).forEach(marker -> resultSet.get(marker).add(solution.get(marker).asResource().getURI())); unionModel.add(this.sparqlEndpointService.getModelFromResults(query, solution, schema)); }); SPARQLExecutionResult sparqlExecutionResult = new SPARQLExecutionResult(resultSet, unionModel); logger.info(sparqlExecutionResult); return sparqlExecutionResult; }