List of usage examples for org.apache.http.impl.auth BasicScheme BasicScheme
public BasicScheme()
From source file:io.wcm.maven.plugins.contentpackage.AbstractContentPackageMojo.java
/** * Set up http client with credentials/*from w ww .j a v a2 s .c om*/ * @return Http client * @throws MojoExecutionException Mojo execution exception */ protected final CloseableHttpClient getHttpClient() throws MojoExecutionException { try { URI crxUri = new URI(getCrxPackageManagerUrl()); final AuthScope authScope = new AuthScope(crxUri.getHost(), crxUri.getPort()); final Credentials credentials = new UsernamePasswordCredentials(this.userId, this.password); final CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(authScope, credentials); HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultCredentialsProvider(credsProvider) .addInterceptorFirst(new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { // enable preemptive authentication AuthState authState = (AuthState) context .getAttribute(HttpClientContext.TARGET_AUTH_STATE); authState.update(new BasicScheme(), credentials); } }); if (this.relaxedSSLCheck) { SSLContext sslContext = new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); httpClientBuilder.setSSLSocketFactory(sslsf); } return httpClientBuilder.build(); } catch (URISyntaxException ex) { throw new MojoExecutionException("Invalid url: " + getCrxPackageManagerUrl(), ex); } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException ex) { throw new MojoExecutionException("Could not set relaxedSSLCheck", ex); } }
From source file:com.glodon.paas.document.api.AbstractDocumentAPITest.java
private void setAuthCache(HttpHost host, BasicHttpContext context) { AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(host, basicAuth);//from ww w . j av a 2 s. c o m if (context == null && localcontext != null) localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); else context.setAttribute(ClientContext.AUTH_CACHE, authCache); }
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()); }/*from w w w. j ava2 s .com*/ 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:org.apache.hadoop.gateway.shell.Hadoop.java
private CloseableHttpClient createClient(ClientContext clientContext) throws GeneralSecurityException { // SSL// w ww .j a v a2 s . co m 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:fr.univsavoie.ltp.client.LoginActivity.java
/** * Pav de code permetant de se connecter de faon scuris au serveur *///from ww w .j a v a 2s. c o m private void auth() { try { HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } }; // Setup a custom SSL Factory object which simply ignore the certificates validation and accept all type of self signed certificates SSLSocketFactory sslFactory = new SimpleSSLSocketFactory(null); sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // Enable HTTP parameters HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); // Register the HTTP and HTTPS Protocols. For HTTPS, register our custom SSL Factory object. SchemeRegistry registry = new SchemeRegistry(); // registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sslFactory, 443)); // Create a new connection manager using the newly created registry and then create a new HTTP client using this connection manager ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); httpClient = new DefaultHttpClient(ccm, params); CredentialsProvider authCred = new BasicCredentialsProvider(); Credentials creds = new UsernamePasswordCredentials(login.getText().toString(), password.getText().toString()); authCred.setCredentials(AuthScope.ANY, creds); httpClient.addRequestInterceptor(preemptiveAuth, 0); httpClient.setCredentialsProvider(authCred); } catch (Exception e) { Log.e("Catch", "Auth: " + e.getLocalizedMessage()); } }
From source file:org.xwiki.eclipse.storage.rest.XWikiRestClient.java
protected HttpResponse executeDelete(URI uri) throws Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password); HttpDelete request = new HttpDelete(uri); request.addHeader(new BasicScheme().authenticate(creds, request)); HttpResponse response = httpClient.execute(request); return response; }
From source file:com.jive.myco.seyren.core.util.graphite.GraphiteHttpClient.java
private HttpClient createHttpClient() { HttpClientBuilder clientBuilder = HttpClientBuilder.create().setConnectionManager(createConnectionManager()) .setDefaultRequestConfig(RequestConfig.custom() .setConnectionRequestTimeout(graphiteConnectionRequestTimeout) .setConnectTimeout(graphiteConnectTimeout).setSocketTimeout(graphiteSocketTimeout).build()); // Set auth header for graphite if username and password are provided if (!StringUtils.isEmpty(graphiteUsername) && !StringUtils.isEmpty(graphitePassword)) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(graphiteUsername, graphitePassword)); clientBuilder.setDefaultCredentialsProvider(credentialsProvider); context.setAttribute("preemptive-auth", new BasicScheme()); clientBuilder.addInterceptorFirst(new PreemptiveAuth()); }// ww w. j a v a2 s .c o m return clientBuilder.build(); }
From source file:org.fcrepo.integration.http.api.AbstractResourceIT.java
/** * Execute an HTTP request with preemptive basic authentication. * * @param request the request to execute * @param username usename to use//from www . j ava2 s .c o m * @param password password to use * @return the open responses * @throws IOException in case of IOException */ @SuppressWarnings("resource") protected CloseableHttpResponse executeWithBasicAuth(final HttpUriRequest request, final String username, final String password) throws IOException { final HttpHost target = new HttpHost(HOSTNAME, SERVER_PORT, PROTOCOL); final CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(username, password)); final CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider) .build(); final AuthCache authCache = new BasicAuthCache(); final BasicScheme basicAuth = new BasicScheme(); authCache.put(target, basicAuth); final HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); return httpclient.execute(request, localContext); }
From source file:com.anaplan.client.transport.ApacheHttpProvider.java
/** {@inheritDoc} */ @Override/*from w ww .ja v a 2s. c om*/ public void setServiceCredentials(Credentials serviceCredentials) throws AnaplanAPITransportException { super.setServiceCredentials(serviceCredentials); if (getServiceLocation() != null) { AuthCache authCache = new BasicAuthCache(); BasicScheme basicScheme = new BasicScheme(); authCache.put(httpHost, basicScheme); httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache); } }