List of usage examples for org.apache.http.impl.auth BasicScheme BasicScheme
public BasicScheme()
From source file:com.bosch.cr.examples.inventorybrowser.server.ProxyServlet.java
@Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String auth = req.getHeader("Authorization"); if (auth == null) { resp.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for Bosch IoT Things\""); resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); return;/*from w w w. jav a 2 s . co m*/ } try { long time = System.currentTimeMillis(); CloseableHttpClient c = getHttpClient(); String targetUrl = URL_PREFIX + req.getPathInfo() + (req.getQueryString() != null ? ("?" + req.getQueryString()) : ""); BasicHttpRequest targetReq = new BasicHttpRequest(req.getMethod(), targetUrl); String user = ""; if (auth.toUpperCase().startsWith("BASIC ")) { String userpassDecoded = new String( new sun.misc.BASE64Decoder().decodeBuffer(auth.substring("BASIC ".length()))); user = userpassDecoded.substring(0, userpassDecoded.indexOf(':')); String pass = userpassDecoded.substring(userpassDecoded.indexOf(':') + 1); UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass); targetReq.addHeader(new BasicScheme().authenticate(creds, targetReq, null)); } targetReq.addHeader("x-cr-api-token", props.getProperty("apiToken")); CloseableHttpResponse targetResp = c.execute(targetHost, targetReq); System.out.println("Request: " + targetHost + targetUrl + ", user " + user + " -> " + (System.currentTimeMillis() - time) + " msec: " + targetResp.getStatusLine()); resp.setStatus(targetResp.getStatusLine().getStatusCode()); targetResp.getEntity().writeTo(resp.getOutputStream()); } catch (IOException | AuthenticationException ex) { throw new RuntimeException(ex); } }
From source file:org.pentaho.reporting.libraries.pensol.vfs.LocalFileModel.java
public LocalFileModel(final String url, final HttpClientManager.HttpClientBuilderFacade clientBuilder, final String username, final String password, final String hostName, int port) { if (url == null) { throw new NullPointerException(); }// w w w .j ava 2 s .c o m this.url = url; this.username = username; this.password = password; this.context = HttpClientContext.create(); if (!StringUtil.isEmpty(hostName)) { // Preemptive Basic Authentication HttpHost target = new HttpHost(hostName, port, "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 this.context.setAuthCache(authCache); } clientBuilder.setCookieSpec(CookieSpecs.DEFAULT); clientBuilder.setMaxRedirects(10); clientBuilder.allowCircularRedirects(); clientBuilder.allowRelativeRedirect(); }
From source file:org.eclipse.mylyn.commons.repositories.http.core.CommonHttpClient.java
private void prepareRequest(HttpRequestBase request, IOperationMonitor monitor) { UserCredentials httpCredentials = location.getCredentials(httpAuthenticationType); if (httpCredentials != null) { HttpUtil.configureAuthentication(getHttpClient(), location, httpCredentials); if (isPreemptiveAuthenticationEnabled()) { // create or pre-populate auth cache HttpHost host = HttpUtil.createHost(request); Object authCache = getContext().getAttribute(ClientContext.AUTH_CACHE); if (authCache == null) { authCache = new BasicAuthCache(); getContext().setAttribute(ClientContext.AUTH_CACHE, authCache); }/* w w w . j a va 2 s. c o m*/ if (authCache instanceof BasicAuthCache) { if (((BasicAuthCache) authCache).get(host) == null) { ((BasicAuthCache) authCache).put(host, new BasicScheme()); } } } } HttpUtil.configureProxy(getHttpClient(), location); CertificateCredentials socketCredentials = location.getCredentials(AuthenticationType.CERTIFICATE); if (socketCredentials != null) { SslSupport support = new SslSupport(new TrustManager[] { new TrustAllTrustManager() }, socketCredentials.getKeyStoreFileName(), socketCredentials.getPassword(), socketCredentials.getKeyStoreType()); request.getParams().setParameter(SslSupport.class.getName(), support); } else { // remove the token that associates certificate credentials with the connection getContext().removeAttribute(ClientContext.USER_TOKEN); } getContext().setAttribute(HttpUtil.CONTEXT_KEY_MONITOR_THREAD, getMonitorThread()); }
From source file:biocode.fims.ezid.EzidService.java
/** * Log into the EZID service using account credentials provided by EZID. The cookie * returned by EZID is cached in a local CookieStore for the duration of the EzidService, * and so subsequent calls using this instance of the service will function as * fully authenticated. An exception is thrown if authentication fails. * * @param username to identify the user account from EZID * @param password the secret password for this account * * @throws EzidException if authentication fails for any reason *//*from w w w.ja v a2 s . c o m*/ public void login(String username, String password) throws EzidException { String msg; try { URI serviceUri = new URI(LOGIN_SERVICE); HttpHost targetHost = new HttpHost(serviceUri.getHost(), serviceUri.getPort(), serviceUri.getScheme()); httpClient.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password)); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); // DEBUGGING ONLY, CAN COMMENT OUT WHEN FULLY WORKING.... //System.out.println("authCache: " + authCache.toString()); ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() { public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toByteArray(entity); } else { return null; } } }; byte[] body = null; HttpGet httpget = new HttpGet(LOGIN_SERVICE); body = httpClient.execute(httpget, handler, localcontext); String message = new String(body); msg = parseIdentifierResponse(message); // DEBUGGING ONLY, CAN COMMENT OUT WHEN FULLY WORKING.... /* org.apache.http.client.CookieStore cookieStore = httpClient.getCookieStore(); System.out.println("\n\nCookies : "); List<Cookie> cookies = cookieStore.getCookies(); for (int i = 0; i < cookies.size(); i++) { System.out.println("Cookie: " + cookies.get(i)); } */ } catch (URISyntaxException e) { //System.out.println("URI SyntaxError Exception in LOGIN"); throw new EzidException("Bad syntax for uri: " + LOGIN_SERVICE, e); } catch (ClientProtocolException e) { //System.out.println("ClientProtocol Exception in LOGIN"); throw new EzidException(e); } catch (IOException e) { //System.out.println("IO Exception in LOGIN"); throw new EzidException(e); } //System.out.println("Seems to be a successful LOGIN, msg= " + msg.toString()); }
From source file:org.fcrepo.integration.AbstractResourceIT.java
protected HttpResponse 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)); try (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); final CloseableHttpResponse response = httpclient.execute(request, localContext); return response; }// w w w. j a v a 2 s . c om }
From source file:com.vmware.photon.controller.nsxclient.RestClient.java
/** * Creates a HTTP client context with preemptive basic authentication. */// w ww . j a v a 2 s . co m private HttpClientContext getHttpClientContext(String target, String username, String password) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); HttpHost targetHost = HttpHost.create(target); AuthCache authCache = new BasicAuthCache(); authCache.put(targetHost, new BasicScheme()); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); context.setAuthCache(authCache); return context; }
From source file:securitytools.veracode.VeracodeClient.java
/** * Constructs a new VeracodeClient using the specified configuration. * /* w w w . j a v a 2 s. c om*/ * @param credentials Credentials used to access Veracode services. * @param clientConfiguration Client configuration for options such as proxy * settings, user-agent header, and network timeouts. */ public VeracodeClient(VeracodeCredentials credentials, ClientConfiguration clientConfiguration) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(TARGET), credentials); AuthCache authCache = new BasicAuthCache(); authCache.put(TARGET, new BasicScheme()); context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); context.setAuthCache(authCache); try { client = HttpClientFactory.build(clientConfiguration); } catch (NoSuchAlgorithmException nsae) { throw new VeracodeClientException(nsae.getMessage(), nsae); } }
From source file:com.bosch.cr.integration.helloworld.ProxyServlet.java
@Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String auth = req.getHeader("Authorization"); if (auth == null) { resp.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for Bosch IoT Things\""); resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); return;//from w w w .j a v a 2s. c o m } try { long time = System.currentTimeMillis(); CloseableHttpClient c = getHttpClient(); String targetUrl = URL_PREFIX + req.getPathInfo() + (req.getQueryString() != null ? ("?" + req.getQueryString()) : ""); BasicHttpRequest targetReq = new BasicHttpRequest(req.getMethod(), targetUrl); String user = ""; if (auth.toUpperCase().startsWith("BASIC ")) { String userpassDecoded = new String( new sun.misc.BASE64Decoder().decodeBuffer(auth.substring("BASIC ".length()))); user = userpassDecoded.substring(0, userpassDecoded.indexOf(':')); String pass = userpassDecoded.substring(userpassDecoded.indexOf(':') + 1); UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass); targetReq.addHeader(new BasicScheme().authenticate(creds, targetReq, null)); } targetReq.addHeader("x-cr-api-token", req.getHeader("x-cr-api-token")); CloseableHttpResponse targetResp = c.execute(targetHost, targetReq); System.out.println("Request: " + targetHost + targetUrl + ", user " + user + " -> " + (System.currentTimeMillis() - time) + " msec: " + targetResp.getStatusLine()); resp.setStatus(targetResp.getStatusLine().getStatusCode()); targetResp.getEntity().writeTo(resp.getOutputStream()); } catch (IOException | AuthenticationException ex) { throw new RuntimeException(ex); } }
From source file:com.bosch.cr.integration.hello_world_ui.ProxyServlet.java
@Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String auth = req.getHeader("Authorization"); if (auth == null) { resp.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for CR\""); resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); return;// w w w . j a v a 2 s . c om } try { long time = System.currentTimeMillis(); CloseableHttpClient c = getHttpClient(); String targetUrl = URL_PREFIX + req.getPathInfo() + (req.getQueryString() != null ? ("?" + req.getQueryString()) : ""); BasicHttpRequest targetReq = new BasicHttpRequest(req.getMethod(), targetUrl); String user = ""; if (auth.toUpperCase().startsWith("BASIC ")) { String userpassDecoded = new String( new sun.misc.BASE64Decoder().decodeBuffer(auth.substring("BASIC ".length()))); user = userpassDecoded.substring(0, userpassDecoded.indexOf(':')); String pass = userpassDecoded.substring(userpassDecoded.indexOf(':') + 1); UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass); targetReq.addHeader(new BasicScheme().authenticate(creds, targetReq, null)); } targetReq.addHeader("x-cr-api-token", req.getHeader("x-cr-api-token")); CloseableHttpResponse targetResp = c.execute(targetHost, targetReq); System.out.println("Request: " + targetHost + targetUrl + ", user " + user + " -> " + (System.currentTimeMillis() - time) + " msec: " + targetResp.getStatusLine()); resp.setStatus(targetResp.getStatusLine().getStatusCode()); targetResp.getEntity().writeTo(resp.getOutputStream()); } catch (IOException | AuthenticationException ex) { throw new RuntimeException(ex); } }
From source file:ch.cern.db.flume.sink.elasticsearch.client.ElasticSearchRestClient.java
@Override public void execute() throws Exception { int statusCode = 0, triesCount = 0; HttpResponse response = null;/*from ww w. j ava 2 s. c om*/ String entity; synchronized (bulkBuilder) { entity = bulkBuilder.toString(); bulkBuilder = new StringBuilder(); } while (statusCode != HttpStatus.SC_OK && triesCount < serversList.size()) { triesCount++; String host = serversList.get(); String url = host + "/" + BULK_ENDPOINT; HttpPost httpRequest = new HttpPost(url); if (username != null && password != null) { UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password); httpRequest.addHeader(new BasicScheme().authenticate(creds, httpRequest, new BasicHttpContext())); } httpRequest.setEntity(new StringEntity(entity)); response = httpClient.execute(httpRequest); statusCode = response.getStatusLine().getStatusCode(); logger.info("Status code from elasticsearch: " + statusCode); if (response.getEntity() != null) logger.debug("Status message from elasticsearch: " + EntityUtils.toString(response.getEntity(), "UTF-8")); } if (statusCode != HttpStatus.SC_OK) { if (response.getEntity() != null) { throw new EventDeliveryException(EntityUtils.toString(response.getEntity(), "UTF-8")); } else { throw new EventDeliveryException("Elasticsearch status code was: " + statusCode); } } }