List of usage examples for org.apache.http.auth AuthScope ANY
AuthScope ANY
To view the source code for org.apache.http.auth AuthScope ANY.
Click Source Link
From source file:org.sonatype.nexus.proxy.storage.remote.httpclient.RemoteStorageContextCustomizer.java
@VisibleForTesting public void applyAuthenticationConfig(final Builder builder, final RemoteAuthenticationSettings ras, final HttpHost proxyHost) { if (ras != null) { String authScope = "target"; if (proxyHost != null) { authScope = proxyHost.toHostString() + " proxy"; }/* ww w.java 2 s . c om*/ final List<String> authorisationPreference = Lists.newArrayListWithExpectedSize(3); authorisationPreference.add(AuthSchemes.DIGEST); authorisationPreference.add(AuthSchemes.BASIC); Credentials credentials = null; if (ras instanceof ClientSSLRemoteAuthenticationSettings) { throw new IllegalArgumentException("SSL client authentication not yet supported!"); } else if (ras instanceof NtlmRemoteAuthenticationSettings) { final NtlmRemoteAuthenticationSettings nras = (NtlmRemoteAuthenticationSettings) ras; // Using NTLM auth, adding it as first in policies authorisationPreference.add(0, AuthSchemes.NTLM); log.debug("{} authentication setup for NTLM domain '{}'", authScope, nras.getNtlmDomain()); credentials = new NTCredentials(nras.getUsername(), nras.getPassword(), nras.getNtlmHost(), nras.getNtlmDomain()); } else if (ras instanceof UsernamePasswordRemoteAuthenticationSettings) { final UsernamePasswordRemoteAuthenticationSettings uras = (UsernamePasswordRemoteAuthenticationSettings) ras; log.debug("{} authentication setup for remote storage with username '{}'", authScope, uras.getUsername()); credentials = new UsernamePasswordCredentials(uras.getUsername(), uras.getPassword()); } if (credentials != null) { if (proxyHost != null) { builder.setCredentials(new AuthScope(proxyHost), credentials); builder.getRequestConfigBuilder().setProxyPreferredAuthSchemes(authorisationPreference); } else { builder.setCredentials(AuthScope.ANY, credentials); builder.getRequestConfigBuilder().setTargetPreferredAuthSchemes(authorisationPreference); } } } }
From source file:uk.co.bubobubo.web.HttpClientProxy.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // Make the Request //note: we won't transfer the protocol version because I'm not sure it would truly be compatible String method = servletRequest.getMethod(); String proxyRequestUri = rewriteUrlFromRequest(servletRequest); HttpRequest proxyRequest;/* w w w .j a v a2s . c o m*/ //spec: RFC 2616, sec 4.3: either these two headers signal that there is a message body. if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); // Add the input entity (streamed) // note: we don't bother ensuring we close the servletInputStream since the container handles it eProxyRequest.setEntity( new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength())); proxyRequest = eProxyRequest; } else proxyRequest = new BasicHttpRequest(method, proxyRequestUri); copyRequestHeaders(servletRequest, proxyRequest); try { // Execute the request if (doLog) { log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } proxyRequest.removeHeaders("authorization"); if (targetUri.getUserInfo() != null && !targetUri.getUserInfo().equalsIgnoreCase("") && !targetUri.getUserInfo().equalsIgnoreCase(":")) { Credentials credentials = new UsernamePasswordCredentials(targetUri.getUserInfo().split(":")[0], targetUri.getUserInfo().split(":")[1]); proxyClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); } HttpResponse proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest); // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { //just to be sure, but is probably a no-op EntityUtils.consume(proxyResponse.getEntity()); return; } // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the // reason along too. //noinspection deprecation servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); copyResponseHeaders(proxyResponse, servletResponse); // Send the content to the client copyResponseEntity(proxyResponse, servletResponse); } catch (Exception e) { //abort request, according to best practice with HttpClient if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } if (e instanceof RuntimeException) throw (RuntimeException) e; if (e instanceof ServletException) throw (ServletException) e; if (e instanceof IOException) throw (IOException) e; throw new RuntimeException(e); } }
From source file:com.heneryh.aquanotes.io.ApexExecutor.java
/** * Execute this {@link HttpUriRequest}, passing a valid response through * {@link XmlHandler#parseAndApply(XmlPullParser, ContentResolver)}. *//*from w ww . j a v a2 s .c o m*/ public void executeWhySeparate(HttpUriRequest request, DefaultHandler xmlParser, String user, String pw) throws HandlerException { try { // Create credentials for basic auth UsernamePasswordCredentials c = new UsernamePasswordCredentials(user, pw); BasicCredentialsProvider cP = new BasicCredentialsProvider(); cP.setCredentials(AuthScope.ANY, c); ((DefaultHttpClient) mHttpClient).setCredentialsProvider(cP); /** * Execute the command and check the status */ final HttpResponse resp = mHttpClient.execute(request); final int status = resp.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { throw new HandlerException( "Unexpected server response " + resp.getStatusLine() + " for " + request.getRequestLine()); } final InputStream input = resp.getEntity().getContent(); try { NewXmlHandler.parseAndStore(input, controllerUri, xmlParser); } catch (HandlerException e) { throw new HandlerException("Malformed response for " + request.getRequestLine(), e); } finally { if (input != null) input.close(); } } catch (HandlerException e) { throw e; } catch (IOException e) { throw new HandlerException("Problem reading remote response for " + request.getRequestLine(), e); } }
From source file:com.ettrema.httpclient.Host.java
public Host(String server, String rootPath, Integer port, String user, String password, ProxyDetails proxyDetails, int timeoutMillis, Cache<Folder, List<Resource>> cache, FileSyncer fileSyncer) {/* w ww .j a v a 2 s .c o m*/ super((cache != null ? cache : new MemoryCache<Folder, List<Resource>>("resource-cache-default", 50, 20))); if (server == null) { throw new IllegalArgumentException("host name cannot be null"); } this.rootPath = rootPath; this.timeout = timeoutMillis; this.server = server; this.port = port; this.user = user; this.password = password; client = new MyDefaultHttpClient(); HttpRequestRetryHandler handler = new NoRetryHttpRequestRetryHandler(); client.setHttpRequestRetryHandler(handler); HttpParams params = client.getParams(); HttpConnectionParams.setConnectionTimeout(params, 10000); HttpConnectionParams.setSoTimeout(params, 10000); if (user != null) { client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password)); PreemptiveAuthInterceptor interceptor = new PreemptiveAuthInterceptor(); client.addRequestInterceptor(interceptor); } if (proxyDetails != null) { if (proxyDetails.isUseSystemProxy()) { System.setProperty("java.net.useSystemProxies", "true"); } else { System.setProperty("java.net.useSystemProxies", "false"); if (proxyDetails.getProxyHost() != null && proxyDetails.getProxyHost().length() > 0) { HttpHost proxy = new HttpHost(proxyDetails.getProxyHost(), proxyDetails.getProxyPort(), "http"); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (proxyDetails.hasAuth()) { client.getCredentialsProvider().setCredentials( new AuthScope(proxyDetails.getProxyHost(), proxyDetails.getProxyPort()), new UsernamePasswordCredentials(proxyDetails.getUserName(), proxyDetails.getPassword())); } } } } transferService = new TransferService(client, connectionListeners); transferService.setTimeout(timeoutMillis); this.fileSyncer = fileSyncer; }
From source file:fr.cnes.sitools.metacatalogue.resources.proxyservices.RedirectorHttps.java
/** * CloseableHttpResponse/*from w w w . ja v a 2 s . com*/ * * @return * @throws ClientProtocolException * @throws IOException */ public CloseableHttpResponse getCloseableResponse(String url, Series<Cookie> cookies) throws ClientProtocolException, IOException { HttpClientBuilder httpclientBuilder = HttpClients.custom(); if (withproxy) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( ProxySettings.getProxyUser(), ProxySettings.getProxyPassword())); httpclientBuilder.setDefaultCredentialsProvider(credsProvider).build(); } CloseableHttpClient httpclient = httpclientBuilder.build(); HttpClientContext context = HttpClientContext.create(); CookieStore cookieStore = new BasicCookieStore(); Iterator<Cookie> iter = cookies.iterator(); while (iter.hasNext()) { Cookie restCookie = iter.next(); BasicClientCookie cookie = new BasicClientCookie(restCookie.getName(), restCookie.getValue()); // cookie.setDomain(restCookie.getDomain()); cookie.setDomain(getDomainName(url)); cookie.setPath(restCookie.getPath()); cookie.setSecure(true); // cookie.setExpiryDate(restCookie); cookieStore.addCookie(cookie); } context.setCookieStore(cookieStore); HttpGet httpget = new HttpGet(url); Builder configBuilder = RequestConfig.custom(); if (withproxy) { HttpHost proxy = new HttpHost(ProxySettings.getProxyHost(), Integer.parseInt(ProxySettings.getProxyPort()), "http"); configBuilder.setProxy(proxy).build(); } RequestConfig config = configBuilder.build(); httpget.setConfig(config); return httpclient.execute(httpget, context); }
From source file:org.apache.brooklyn.rest.client.BrooklynApi.java
/** * Creates a ClientExecutor for this BrooklynApi */// w w w . j a v a 2s . c om protected ClientExecutor getClientExecutor(Credentials credentials) { CredentialsProvider provider = new BasicCredentialsProvider(); if (credentials != null) provider.setCredentials(AuthScope.ANY, credentials); CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider) .setDefaultRequestConfig(reqConfSupplier.get()) .setConnectionManager(connectionManagerSupplier.get()).build(); return new ApacheHttpClient4Executor(httpClient); }
From source file:com.jaeksoft.searchlib.crawler.web.database.CredentialItem.java
public void setUpCredentials(CredentialsProvider credentialProvider) { if (StringUtils.isEmpty(username)) return;/*w w w . j a v a 2s.c om*/ Credentials credentials = null; switch (type) { case BASIC_DIGEST: credentials = new UsernamePasswordCredentials(getUsername(), getPassword()); break; case NTLM: credentials = new NTCredentials(getUsername(), getPassword(), getWorkstation(), getDomain()); break; } if (credentials != null) credentialProvider.setCredentials(AuthScope.ANY, credentials); }
From source file:org.activiti.rest.service.api.runtime.SerializableVariablesDiabledTest.java
public void assertResponseStatus(HttpUriRequest request, int expectedStatusCode) { CloseableHttpResponse response = null; try {/* w w w. j a va 2s . c o m*/ CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("kermit", "kermit"); provider.setCredentials(AuthScope.ANY, credentials); HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build(); response = (CloseableHttpResponse) client.execute(request); int statusCode = response.getStatusLine().getStatusCode(); Assert.assertEquals(expectedStatusCode, statusCode); if (client instanceof CloseableHttpClient) { ((CloseableHttpClient) client).close(); } response.close(); } catch (ClientProtocolException e) { Assert.fail(e.getMessage()); } catch (IOException e) { Assert.fail(e.getMessage()); } }
From source file:org.springframework.cloud.dataflow.shell.command.ConfigCommands.java
@CliCommand(value = { "dataflow config server" }, help = "Configure the Spring Cloud Data Flow REST server to use") public String target(@CliOption(mandatory = false, key = { "", "uri" }, help = "the location of the Spring Cloud Data Flow REST endpoint", unspecifiedDefaultValue = Target.DEFAULT_TARGET) String targetUriString, @CliOption(mandatory = false, key = { "username" }, help = "the username for authenticated access to the Admin REST endpoint", unspecifiedDefaultValue = Target.DEFAULT_USERNAME) String targetUsername, @CliOption(mandatory = false, key = { "password" }, help = "the password for authenticated access to the Admin REST endpoint (valid only with a username)", specifiedDefaultValue = Target.DEFAULT_SPECIFIED_PASSWORD, unspecifiedDefaultValue = Target.DEFAULT_UNSPECIFIED_PASSWORD) String targetPassword) { if (!StringUtils.isEmpty(targetPassword) && StringUtils.isEmpty(targetUsername)) { return "A password may be specified only together with a username"; }/*from w ww . j a va 2s .com*/ if (StringUtils.isEmpty(targetPassword) && !StringUtils.isEmpty(targetUsername)) { // read password from the command line targetPassword = userInput.prompt("Password", "", false); } try { this.targetHolder.setTarget(new Target(targetUriString, targetUsername, targetPassword)); if (StringUtils.hasText(targetUsername) && StringUtils.hasText(targetPassword)) { final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( targetHolder.getTarget().getTargetCredentials().getUsername(), targetHolder.getTarget().getTargetCredentials().getPassword())); final CloseableHttpClient httpClient = HttpClientBuilder.create() .setDefaultCredentialsProvider(credentialsProvider).build(); final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); this.restTemplate.setRequestFactory(requestFactory); } this.shell.setDataFlowOperations( new DataFlowTemplate(targetHolder.getTarget().getTargetUri(), this.restTemplate)); return (String.format("Successfully targeted %s", targetUriString)); } catch (Exception e) { this.targetHolder.getTarget().setTargetException(e); this.shell.setDataFlowOperations(null); if (e instanceof DataFlowServerException) { String message = String.format("Unable to parse server response: %s - at URI '%s'.", e.getMessage(), targetUriString); if (logger.isDebugEnabled()) { logger.debug(message, e); } else { logger.warn(message); } return message; } else { return (String.format("Unable to contact Data Flow Server at '%s': '%s'.", targetUriString, e.toString())); } } }