List of usage examples for org.apache.http.client AuthCache put
void put(HttpHost host, AuthScheme authScheme);
From source file:com.unboundid.scim.sdk.PreemptiveAuthInterceptor.java
/** * {@inheritDoc}// w w w . j a v a 2 s . co m */ @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (target.getPort() < 0) { SchemeRegistry schemeRegistry = (SchemeRegistry) context.getAttribute(ClientContext.SCHEME_REGISTRY); Scheme scheme = schemeRegistry.getScheme(target); target = new HttpHost(target.getHostName(), scheme.resolvePort(target.getPort()), target.getSchemeName()); } AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE); if (authCache == null) { authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(target, basicAuth); context.setAttribute(ClientContext.AUTH_CACHE, authCache); return; } CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); if (credsProvider == null) { return; } final AuthState targetState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); if (targetState != null && targetState.getState() == AuthProtocolState.UNCHALLENGED) { final AuthScheme authScheme = authCache.get(target); if (authScheme != null) { doPreemptiveAuth(target, authScheme, targetState, credsProvider); } } final HttpHost proxy = (HttpHost) context.getAttribute(ExecutionContext.HTTP_PROXY_HOST); final AuthState proxyState = (AuthState) context.getAttribute(ClientContext.PROXY_AUTH_STATE); if (proxy != null && proxyState != null && proxyState.getState() == AuthProtocolState.UNCHALLENGED) { final AuthScheme authScheme = authCache.get(proxy); if (authScheme != null) { doPreemptiveAuth(proxy, authScheme, proxyState, credsProvider); } } }
From source file:io.kahu.hawaii.util.call.http.HttpRequestBuilder.java
private void addAuthentication(AbortableHttpRequest<T> request, URI uri) { if (credentials != null) { CredentialsProvider credentialsProvider = null; switch (credentials.getAuthenticationType()) { case BASIC: // fall-through to default default:/*from w w w. j a va2s . co m*/ BasicScheme authenticationScheme = new BasicScheme(); credentialsProvider = new BasicCredentialsProvider(); // Explicitly set the AuthScope to ANY_REALM in order to get // 'preemptive authentication' to work credentialsProvider.setCredentials( new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_REALM, authenticationScheme.getSchemeName()), new UsernamePasswordCredentials(credentials.getUsername(), credentials.getPassword())); // Create an auth cache for preemptive authentication. AuthCache authCache = new BasicAuthCache(); authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), authenticationScheme); request.getHttpClientContext().setAuthCache(authCache); break; } request.getHttpClientContext().setCredentialsProvider(credentialsProvider); } }
From source file:org.apache.hadoop.gateway.shell.Hadoop.java
private CloseableHttpClient createClient(ClientContext clientContext) throws GeneralSecurityException { // SSL/*w ww.j a v a 2 s .c om*/ HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; TrustStrategy trustStrategy = null; if (clientContext.connection().secure()) { hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier(); } else { trustStrategy = TrustSelfSignedStrategy.INSTANCE; System.out.println("**************** WARNING ******************\n" + "This is an insecure client instance and may\n" + "leave the interactions subject to a man in\n" + "the middle attack. Please use the login()\n" + "method instead of loginInsecure() for any\n" + "sensitive or production usecases.\n" + "*******************************************"); } KeyStore trustStore = getTrustStore(); SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore, trustStrategy).build(); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", new SSLConnectionSocketFactory(sslContext, hostnameVerifier)).build(); // Pool PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry); connectionManager.setMaxTotal(clientContext.pool().maxTotal()); connectionManager.setDefaultMaxPerRoute(clientContext.pool().defaultMaxPerRoute()); ConnectionConfig connectionConfig = ConnectionConfig.custom() .setBufferSize(clientContext.connection().bufferSize()).build(); connectionManager.setDefaultConnectionConfig(connectionConfig); SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(clientContext.socket().keepalive()) .setSoLinger(clientContext.socket().linger()) .setSoReuseAddress(clientContext.socket().reuseAddress()) .setSoTimeout(clientContext.socket().timeout()).setTcpNoDelay(clientContext.socket().tcpNoDelay()) .build(); connectionManager.setDefaultSocketConfig(socketConfig); // Auth URI uri = URI.create(clientContext.url()); host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); CredentialsProvider credentialsProvider = null; if (clientContext.username() != null && clientContext.password() != null) { credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort()), new UsernamePasswordCredentials(clientContext.username(), clientContext.password())); AuthCache authCache = new BasicAuthCache(); BasicScheme authScheme = new BasicScheme(); authCache.put(host, authScheme); context = new BasicHttpContext(); context.setAttribute(org.apache.http.client.protocol.HttpClientContext.AUTH_CACHE, authCache); } return HttpClients.custom().setConnectionManager(connectionManager) .setDefaultCredentialsProvider(credentialsProvider).build(); }
From source file:com.redhat.jenkins.nodesharing.RestEndpoint.java
private @Nonnull HttpClientContext getAuthenticatingContext(@Nonnull HttpRequestBase method) { AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(URIUtils.extractHost(method.getURI()), basicAuth); CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(AuthScope.ANY, new org.apache.http.auth.UsernamePasswordCredentials( creds.getUsername(), creds.getPassword().getPlainText())); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(provider); context.setAuthCache(authCache);// w ww . j ava 2 s . c om return context; }
From source file:org.zalando.stups.tokens.AccessTokenRefresher.java
private AccessToken createToken(final AccessTokenConfiguration tokenConfig) { try {// w w w.j a va2 s. c o m // collect credentials final ClientCredentials clientCredentials = configuration.getClientCredentialsProvider().get(); final UserCredentials userCredentials = configuration.getUserCredentialsProvider().get(); // prepare basic auth credentials final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials( new AuthScope(configuration.getAccessTokenUri().getHost(), configuration.getAccessTokenUri().getPort()), new UsernamePasswordCredentials(clientCredentials.getId(), clientCredentials.getSecret())); // create a new client that targets our host with basic auth enabled final CloseableHttpClient client = HttpClients.custom() .setDefaultCredentialsProvider(credentialsProvider).build(); final HttpHost host = new HttpHost(configuration.getAccessTokenUri().getHost(), configuration.getAccessTokenUri().getPort(), configuration.getAccessTokenUri().getScheme()); final HttpPost request = new HttpPost(configuration.getAccessTokenUri()); // prepare the request body final List<NameValuePair> values = new ArrayList<NameValuePair>() { { add(new BasicNameValuePair("grant_type", "password")); add(new BasicNameValuePair("username", userCredentials.getUsername())); add(new BasicNameValuePair("password", userCredentials.getPassword())); add(new BasicNameValuePair("scope", joinScopes(tokenConfig.getScopes()))); } }; request.setEntity(new UrlEncodedFormEntity(values)); // enable basic auth for the request final AuthCache authCache = new BasicAuthCache(); final BasicScheme basicAuth = new BasicScheme(); authCache.put(host, basicAuth); final HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); // execute! final CloseableHttpResponse response = client.execute(host, request, localContext); try { // success status code? final int status = response.getStatusLine().getStatusCode(); if (status < 200 || status >= 300) { throw AccessTokenEndpointException.from(response); } // get json response final HttpEntity entity = response.getEntity(); final AccessTokenResponse accessTokenResponse = OBJECT_MAPPER .readValue(EntityUtils.toByteArray(entity), AccessTokenResponse.class); // create new access token object final Date validUntil = new Date( System.currentTimeMillis() + (accessTokenResponse.expiresInSeconds * 1000)); return new AccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getTokenType(), accessTokenResponse.getExpiresInSeconds(), validUntil); } finally { response.close(); } } catch (Throwable t) { throw new AccessTokenEndpointException(t.getMessage(), t); } }
From source file:org.ops4j.pax.web.itest.base.client.HttpComponentsWrapper.java
private HttpResponse getHttpResponse(String path, boolean authenticate, BasicHttpContext basicHttpContext, boolean async) throws IOException, KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, CertificateException, AuthenticationException, InterruptedException, ExecutionException { HttpHost targetHost = getHttpHost(path); BasicHttpContext localcontext = basicHttpContext == null ? new BasicHttpContext() : basicHttpContext; HttpGet httpget = new HttpGet(path); for (Map.Entry<String, String> entry : httpHeaders.entrySet()) { LOG.info("adding request-header: {}={}", entry.getKey(), entry.getValue()); httpget.addHeader(entry.getKey(), entry.getValue()); }//www . j a va 2 s . c o m LOG.info("calling remote {} ...", path); HttpResponse response = null; if (!authenticate && basicHttpContext == null) { if (localcontext.getAttribute(ClientContext.AUTH_CACHE) != null) { localcontext.removeAttribute(ClientContext.AUTH_CACHE); } if (!async) { response = httpclient.execute(httpget, context); } else { Future<HttpResponse> future = httpAsyncClient.execute(httpget, context, null); response = future.get(); } } else { UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, 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(targetHost, basicAuth); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); httpget.addHeader(basicAuth.authenticate(creds, httpget, localcontext)); if (!async) { response = httpclient.execute(targetHost, httpget, localcontext); } else { Future<HttpResponse> future = httpAsyncClient.execute(targetHost, httpget, localcontext, null); response = future.get(); } } LOG.info("... responded with: {}", response.getStatusLine().getStatusCode()); return response; }
From source file:com.cheddargetter.client.service.CheddarGetterPaymentService.java
private BasicHttpContext createHttpContext() { AuthCache authCache = new BasicAuthCache(); authCache.put(host, new BasicScheme()); BasicHttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.AUTH_CACHE, authCache); return context; }
From source file:hu.dolphio.tprttapi.service.TrackingFlushServiceTpImpl.java
public TrackingFlushServiceTpImpl(String dateFrom, String dateTo) { this.dateFrom = dateFrom; this.dateTo = dateTo; targetHost = new HttpHost(propertyReader.getTpHost(), 80, "http"); credsProvider = new BasicCredentialsProvider(); Credentials credentials = new UsernamePasswordCredentials(propertyReader.getTpUserName(), propertyReader.getTpPassword()); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), credentials); config = RequestConfig.custom().setSocketTimeout(propertyReader.getConnectionTimeout()) .setConnectTimeout(propertyReader.getConnectionTimeout()).build(); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); clientContext.setAuthCache(authCache); }
From source file:de.adorsys.oauth.loginmodule.HTTPAuthenticationLoginModule.java
private boolean authenticate(String username, String password) throws LoginException { HttpHost targetHost = new HttpHost(restEndpoint.getHost(), restEndpoint.getPort(), restEndpoint.getScheme());//from ww w . j ava 2 s.co m CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password)); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(Consts.UTF_8); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); context.setAuthCache(authCache); HttpGet httpGet = new HttpGet(restEndpoint); CloseableHttpResponse userInfoResponse = null; try { userInfoResponse = HTTP_CLIENT.execute(httpGet, context); if (userInfoResponse.getStatusLine().getStatusCode() != 200) { LOG.error("Authentication failed for user {}, restEndpoint {} HTTP Status {}", username, restEndpoint.toASCIIString(), userInfoResponse.getStatusLine()); throw new LoginException("Authentication failed for user " + username + ", restEndpoint " + restEndpoint.toASCIIString() + " HTTP Status " + userInfoResponse.getStatusLine()); } String userInfoJson = readUserInfo(userInfoResponse); JSONObject userInfo = new JSONObject(userInfoJson); String principalId = userInfo.getString("principal"); if (principalId == null) { LOG.error("could not read field 'principal' for user {}. Response: {}", username, userInfoJson); throw new LoginException( "could not read field 'principal' for user " + username + ". Response: " + userInfoJson); } JSONArray roles = userInfo.getJSONArray("roles"); populateSubject(principalId, roles); // we put them to shared stated that other login providers can also // authenticate sharedState.put("javax.security.auth.login.name", principalId); sharedState.put("javax.security.auth.login.password", password); } catch (IOException e) { throw new IllegalStateException("problem on http backend authentication", e); } finally { if (userInfoResponse != null) { try { userInfoResponse.close(); } catch (IOException e) { ; // NOOP } } } return true; }
From source file:org.apache.hadoop.gateway.GatewaySslFuncTest.java
@Test(timeout = TestUtils.MEDIUM_TIMEOUT) public void testKnox674SslCipherSuiteConfig() throws Exception { LOG_ENTER();/*from w w w. j a va 2s . c om*/ String topoStr = TestUtils.merge(DAT, "test-admin-topology.xml", params); File topoFile = new File(config.getGatewayTopologyDir(), "test-topology.xml"); FileUtils.writeStringToFile(topoFile, topoStr); topos.reloadTopologies(); String username = "guest"; String password = "guest-password"; String serviceUrl = gatewayUrl + "/test-topology/api/v1/version"; HttpHost targetHost = new HttpHost("localhost", gatewayPort, gatewayScheme); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password)); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); CloseableHttpClient client = HttpClients.custom() .setSSLSocketFactory( new SSLConnectionSocketFactory(createInsecureSslContext(), new String[] { "TLSv1.2" }, new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" }, new TrustAllHosts())) .build(); HttpGet request = new HttpGet(serviceUrl); CloseableHttpResponse response = client.execute(request, context); assertThat(the(new StreamSource(response.getEntity().getContent())), hasXPath("/ServerVersion/version")); response.close(); client.close(); gateway.stop(); config.setExcludedSSLCiphers(Arrays.asList(new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" })); config.setIncludedSSLCiphers(Arrays.asList(new String[] { "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" })); startGatewayServer(); serviceUrl = gatewayUrl + "/test-topology/api/v1/version"; try { client = HttpClients.custom() .setSSLSocketFactory( new SSLConnectionSocketFactory(createInsecureSslContext(), new String[] { "TLSv1.2" }, new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" }, new TrustAllHosts())) .build(); request = new HttpGet(serviceUrl); client.execute(request, context); fail("Expected SSLHandshakeException"); } catch (SSLHandshakeException e) { // Expected. client.close(); } client = HttpClients.custom() .setSSLSocketFactory( new SSLConnectionSocketFactory(createInsecureSslContext(), new String[] { "TLSv1.2" }, new String[] { "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" }, new TrustAllHosts())) .build(); request = new HttpGet(serviceUrl); response = client.execute(request, context); assertThat(the(new StreamSource(response.getEntity().getContent())), hasXPath("/ServerVersion/version")); response.close(); client.close(); LOG_EXIT(); }