Java Code Examples for org.apache.http.client.protocol.HttpClientContext#setAuthCache()
The following examples show how to use
org.apache.http.client.protocol.HttpClientContext#setAuthCache() .
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: FormatClientSupport.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
protected CloseableHttpResponse execute(final HttpUriRequest request, String username, String password) throws IOException { log.debug("Authorizing request for {} using credentials provided for username: {}", request.getURI(), username); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); HttpHost host = URIUtils.extractHost(request.getURI()); AuthCache authCache = new BasicAuthCache(); authCache.put(host, new BasicScheme()); HttpClientContext clientContext = new HttpClientContext(httpClientContext); clientContext.setAuthCache(authCache); clientContext.setCredentialsProvider(credsProvider); return execute(request, clientContext); }
Example 2
Source File: WireMockTestClient.java From wiremock-webhooks-extension with Apache License 2.0 | 6 votes |
public WireMockResponse getWithPreemptiveCredentials(String url, int port, String username, String password) { HttpHost target = new HttpHost("localhost", port); HttpClient httpClient = httpClientWithPreemptiveAuth(target, username, password); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(target, basicAuth); HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); try { HttpGet httpget = new HttpGet(url); HttpResponse response = httpClient.execute(target, httpget, localContext); return new WireMockResponse(response); } catch (IOException e) { return throwUnchecked(e, WireMockResponse.class); } }
Example 3
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 4
Source File: DefaultSpringCloudConfigClientGateway.java From quarkus with Apache License 2.0 | 6 votes |
private HttpClientContext setupContext() { final HttpClientContext context = HttpClientContext.create(); if (baseUri.contains("@") || springCloudConfigClientConfig.usernameAndPasswordSet()) { final AuthCache authCache = InMemoryAuthCache.INSTANCE; authCache.put(HttpHost.create(baseUri), new BasicScheme()); context.setAuthCache(authCache); if (springCloudConfigClientConfig.usernameAndPasswordSet()) { final CredentialsProvider provider = new BasicCredentialsProvider(); final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials( springCloudConfigClientConfig.username.get(), springCloudConfigClientConfig.password.get()); provider.setCredentials(AuthScope.ANY, credentials); context.setCredentialsProvider(provider); } } return context; }
Example 5
Source File: TaxiiHandler.java From metron with Apache License 2.0 | 6 votes |
private static HttpClientContext createContext(URL endpoint, String username, String password, int port) { HttpClientContext context = null; HttpHost target = new HttpHost(endpoint.getHost(), port, endpoint.getProtocol()); if (username != null && password != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(username, password)); // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html AuthCache authCache = new BasicAuthCache(); authCache.put(target, new BasicScheme()); // Add AuthCache to the execution context context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); } else { context = null; } return context; }
Example 6
Source File: HTTPClient.java From gocd-build-status-notifier with Apache License 2.0 | 5 votes |
public void postRequest(String updateURL, AuthenticationType authenticationType, String username, String password, String requestBody) throws Exception { CloseableHttpClient httpClient = null; try { HttpPost request = new HttpPost(updateURL); request.addHeader("content-type", "application/json"); request.setEntity(new StringEntity(requestBody)); HttpHost target = getHttpHost(updateURL); AuthCache authCache = getAuthCache(authenticationType, target); HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(target), new UsernamePasswordCredentials(username, password)); httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build(); HttpResponse response = httpClient.execute(request, localContext); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode > 204) { throw new RuntimeException("Error occurred. Status Code: " + statusCode); } } finally { if (httpClient != null) { try { httpClient.close(); } catch (Exception e) { // ignore } } } }
Example 7
Source File: NexusClientFactory.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Nullable public T createClient(final URL repositoryUrl, final String username, final String password) { checkNotNull(repositoryUrl); checkNotNull(username); checkNotNull(password); AuthScope scope = new AuthScope(repositoryUrl.getHost(), -1); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(scope, new UsernamePasswordCredentials(username, password)); RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); requestConfigBuilder.setExpectContinueEnabled(true); AuthCache authCache = new BasicAuthCache(); authCache.put(new HttpHost(repositoryUrl.getHost(), repositoryUrl.getPort()), new BasicScheme()); HttpClientContext httpClientContext = HttpClientContext.create(); httpClientContext.setAuthCache(authCache); httpClientContext.setRequestConfig(requestConfigBuilder.build()); try { return createClient( HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build(), httpClientContext, repositoryUrl.toURI() ); } catch (URISyntaxException e) { log.warn("Uri exception creating Client", e); } return null; }
Example 8
Source File: ManageQpidJMSResources.java From qpid-broker-j with Apache License 2.0 | 5 votes |
private HttpClientContext getHttpClientContext(final HttpHost management) { final BasicAuthCache authCache = new BasicAuthCache(); authCache.put(management, new BasicScheme()); HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); return localContext; }
Example 9
Source File: JavaBrokerAdmin.java From qpid-broker-j with Apache License 2.0 | 5 votes |
private HttpClientContext getHttpClientContext(final HttpHost management) { final BasicAuthCache authCache = new BasicAuthCache(); authCache.put(management, new BasicScheme()); HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); return localContext; }
Example 10
Source File: DigestAuthHandler.java From restfiddle with Apache License 2.0 | 5 votes |
public HttpClientContext preemptive() { AuthCache authCache = new BasicAuthCache(); DigestScheme digestAuth = new DigestScheme(); digestAuth.overrideParamter("realm", ""); digestAuth.overrideParamter("nonce", ""); // TODO : Add target // authCache.put(target, digestAuth); HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); return localContext; }
Example 11
Source File: ContextBuilder.java From cs-actions with Apache License 2.0 | 5 votes |
public HttpClientContext build() { if (StringUtils.isEmpty(preemptiveAuth)) { preemptiveAuth = "true"; } HttpClientContext context = HttpClientContext.create(); if (authTypes.size() == 1 && Boolean.parseBoolean(preemptiveAuth) && !authTypes.contains(AuthTypes.ANONYMOUS)) { AuthCache authCache = new BasicAuthCache(); authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), authSchemeLookup.lookup(authTypes.iterator().next()).create(context)); context.setCredentialsProvider(credentialsProvider); context.setAuthCache(authCache); } return context; }
Example 12
Source File: CommonsDataLoader.java From dss with GNU Lesser General Public License v2.1 | 5 votes |
protected HttpContext getHttpContext(final HttpHost targetHost) { // 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); // Add AuthCache to the execution context HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); return localContext; }
Example 13
Source File: GatewayBasicFuncTest.java From knox with Apache License 2.0 | 5 votes |
private String oozieQueryJobStatus( String user, String password, String id, int status ) throws Exception { driver.getMock( "OOZIE" ) .expect() .method( "GET" ) .pathInfo( "/v1/job/" + id ) .respond() .status( HttpStatus.SC_OK ) .content( driver.getResourceBytes( "oozie-job-show-info.json" ) ) .contentType( "application/json" ); //NOTE: For some reason REST-assured doesn't like this and ends up failing with Content-Length issues. URL url = new URL( driver.getUrl( "OOZIE" ) + "/v1/job/" + id + ( driver.isUseGateway() ? "" : "?user.name=" + user ) ); HttpHost targetHost = new HttpHost( url.getHost(), url.getPort(), url.getProtocol() ); HttpClientBuilder builder = HttpClientBuilder.create(); CloseableHttpClient client = builder.build(); HttpClientContext context = HttpClientContext.create(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope( targetHost ), new UsernamePasswordCredentials( user, password ) ); context.setCredentialsProvider( credsProvider ); // 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 ); // Add AuthCache to the execution context context.setAuthCache( authCache ); HttpGet request = new HttpGet( url.toURI() ); request.setHeader("X-XSRF-Header", "ksdhfjkhdsjkf"); HttpResponse response = client.execute( targetHost, request, context ); assertThat( response.getStatusLine().getStatusCode(), Matchers.is(status) ); String json = EntityUtils.toString( response.getEntity() ); return JsonPath.from(json).getString( "status" ); }
Example 14
Source File: WebService.java From hop with Apache License 2.0 | 5 votes |
private HttpClient getHttpClient( HttpClientContext context ) { HttpClientManager.HttpClientBuilderFacade clientBuilder = HttpClientManager.getInstance().createBuilder(); String login = environmentSubstitute( meta.getHttpLogin() ); if ( StringUtils.isNotBlank( login ) ) { clientBuilder.setCredentials( login, Encr.decryptPasswordOptionallyEncrypted( environmentSubstitute( meta.getHttpPassword() ) ) ); } int proxyPort = 0; if ( StringUtils.isNotBlank( meta.getProxyHost() ) ) { proxyPort = Const.toInt( environmentSubstitute( meta.getProxyPort() ), 8080 ); clientBuilder.setProxy( meta.getProxyHost(), proxyPort ); } CloseableHttpClient httpClient = clientBuilder.build(); if ( proxyPort != 0 ) { // Preemptive authentication HttpHost target = new HttpHost( meta.getProxyHost(), proxyPort, "http" ); // 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( target, basicAuth ); // Add AuthCache to the execution context context.setAuthCache( authCache ); } return httpClient; }
Example 15
Source File: FileDownloader.java From frontend-maven-plugin with Apache License 2.0 | 5 votes |
private HttpClientContext makeLocalContext(URL requestUrl) { // Auth target host HttpHost target = new HttpHost (requestUrl.getHost(), requestUrl.getPort(), requestUrl.getProtocol()); // 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(target, basicAuth); // Add AuthCache to the execution context HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); return localContext; }
Example 16
Source File: HttpClientAdvancedConfigurationIntegrationTest.java From tutorials with MIT License | 4 votes |
@Test public void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException { //given proxyMock.stubFor(get(urlMatching("/private")) .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); serviceMock.stubFor(get(urlEqualTo("/private")) .willReturn(aResponse().withStatus(200))); HttpHost proxy = new HttpHost("localhost", 8090); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); // Client credentials CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials("username_admin", "secret_password")); // 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(proxy, basicAuth); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); context.setAuthCache(authCache); HttpClient httpclient = HttpClients.custom() .setRoutePlanner(routePlanner) .setDefaultCredentialsProvider(credentialsProvider) .build(); //when final HttpGet httpGet = new HttpGet("http://localhost:8089/private"); HttpResponse response = httpclient.execute(httpGet, context); //then assertEquals(response.getStatusLine().getStatusCode(), 200); proxyMock.verify(getRequestedFor(urlEqualTo("/private")).withHeader("Authorization", containing("Basic"))); serviceMock.verify(getRequestedFor(urlEqualTo("/private"))); }
Example 17
Source File: JenKinsBuildService.java From ehousechina with Apache License 2.0 | 4 votes |
private HttpClientContext getHttpClientContext(){ HttpClientContext httpClientContext = HttpClientContext.create(); httpClientContext.setCredentialsProvider(this.getCredentialsProvider()); httpClientContext.setAuthCache(this.getAuthCache()); return httpClientContext; }
Example 18
Source File: GatewayBasicFuncTest.java From knox with Apache License 2.0 | 4 votes |
private String oozieSubmitJob( String user, String password, String request, int status ) throws IOException, URISyntaxException { driver.getMock( "OOZIE" ) .expect() .method( "POST" ) .pathInfo( "/v1/jobs" ) .respond() .status( HttpStatus.SC_CREATED ) .content( driver.getResourceBytes( "oozie-jobs-submit-response.json" ) ) .contentType( "application/json" ); URL url = new URL( driver.getUrl( "OOZIE" ) + "/v1/jobs?action=start" + ( driver.isUseGateway() ? "" : "&user.name=" + user ) ); HttpHost targetHost = new HttpHost( url.getHost(), url.getPort(), url.getProtocol() ); HttpClientBuilder builder = HttpClientBuilder.create(); CloseableHttpClient client = builder.build(); HttpClientContext context = HttpClientContext.create(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope( targetHost ), new UsernamePasswordCredentials( user, password ) ); context.setCredentialsProvider( credsProvider ); // 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 ); // Add AuthCache to the execution context context.setAuthCache( authCache ); HttpPost post = new HttpPost( url.toURI() ); // post.getParams().setParameter( "action", "start" ); StringEntity entity = new StringEntity( request, org.apache.http.entity.ContentType.create( "application/xml", StandardCharsets.UTF_8.name() ) ); post.setEntity( entity ); post.setHeader( "X-XSRF-Header", "ksdjfhdsjkfhds" ); HttpResponse response = client.execute( targetHost, post, context ); assertThat( response.getStatusLine().getStatusCode(), Matchers.is(status) ); String json = EntityUtils.toString( response.getEntity() ); // String json = given() // .log().all() // .auth().preemptive().basic( user, password ) // .queryParam( "action", "start" ) // .contentType( "application/xml;charset=UTF-8" ) // .content( request ) // .then() // .log().all() // .statusCode( status ) // .when().post( getUrl( "OOZIE" ) + "/v1/jobs" + ( isUseGateway() ? "" : "?user.name=" + user ) ).asString(); return JsonPath.from(json).getString( "id" ); }
Example 19
Source File: Http4FileProvider.java From commons-vfs with Apache License 2.0 | 4 votes |
/** * Create an {@link HttpClientContext} object for an http4 file system. * * @param builder Configuration options builder for http4 provider * @param rootName The root path * @param fileSystemOptions The FileSystem options * @param authData The {@code UserAuthentiationData} object * @return an {@link HttpClientContext} object * @throws FileSystemException if an error occurs */ protected HttpClientContext createHttpClientContext(final Http4FileSystemConfigBuilder builder, final GenericFileName rootName, final FileSystemOptions fileSystemOptions, final UserAuthenticationData authData) throws FileSystemException { final HttpClientContext clientContext = HttpClientContext.create(); final CredentialsProvider credsProvider = new BasicCredentialsProvider(); clientContext.setCredentialsProvider(credsProvider); final String username = UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(rootName.getUserName()))); final String password = UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(rootName.getPassword()))); if (username != null && !username.isEmpty()) { credsProvider.setCredentials(new AuthScope(rootName.getHostName(), AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password)); } final HttpHost proxyHost = getProxyHttpHost(builder, fileSystemOptions); if (proxyHost != null) { final UserAuthenticator proxyAuth = builder.getProxyAuthenticator(fileSystemOptions); if (proxyAuth != null) { final UserAuthenticationData proxyAuthData = UserAuthenticatorUtils.authenticate(proxyAuth, new UserAuthenticationData.Type[] { UserAuthenticationData.USERNAME, UserAuthenticationData.PASSWORD }); if (proxyAuthData != null) { final UsernamePasswordCredentials proxyCreds = new UsernamePasswordCredentials( UserAuthenticatorUtils.toString( UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME, null)), UserAuthenticatorUtils.toString( UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD, null))); credsProvider.setCredentials(new AuthScope(proxyHost.getHostName(), AuthScope.ANY_PORT), proxyCreds); } if (builder.isPreemptiveAuth(fileSystemOptions)) { final AuthCache authCache = new BasicAuthCache(); final BasicScheme basicAuth = new BasicScheme(); authCache.put(proxyHost, basicAuth); clientContext.setAuthCache(authCache); } } } return clientContext; }
Example 20
Source File: NexusITSupport.java From nexus-public with Eclipse Public License 1.0 | 4 votes |
/** * @return Context with preemptive auth enabled for Nexus */ protected HttpClientContext clientContext() { HttpClientContext context = HttpClientContext.create(); context.setAuthCache(basicAuthCache()); return context; }