List of usage examples for org.apache.http.auth AuthScope AuthScope
public AuthScope(final String host, final int port)
From source file:org.xwiki.contrib.jira.macro.internal.source.HTTPJIRAFetcher.java
private void setPreemptiveBasicAuthentication(HttpClientContext context, JIRAServer jiraServer, HttpHost targetHost) {// w w w. j a va2 s .c o m // Connect to JIRA using basic authentication if username and password are defined // Note: Set up preemptive basic authentication since JIRA can accept both unauthenticated and authenticated // requests. See https://developer.atlassian.com/server/jira/platform/basic-authentication/ if (StringUtils.isNotBlank(jiraServer.getUsername()) && StringUtils.isNotBlank(jiraServer.getPassword())) { CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(jiraServer.getUsername(), jiraServer.getPassword())); // 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.setCredentialsProvider(provider); context.setAuthCache(authCache); } }
From source file:org.sonatype.nexus.testsuite.security.nexus4257.Nexus4257CookieVerificationIT.java
@Test public void testCookieForStateFullClient() throws Exception { setAnonymousAccess(false);/*from w w w. j ava2 s .c om*/ TestContext context = TestContainer.getInstance().getTestContext(); String username = context.getAdminUsername(); String password = context.getPassword(); String url = this.getBaseNexusUrl() + "content/"; URI nexusBaseURI = new URI(url); DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "SomeUAThatWillMakeMeLookStateful/1.0"); final BasicHttpContext localcontext = new BasicHttpContext(); final HttpHost targetHost = new HttpHost(nexusBaseURI.getHost(), nexusBaseURI.getPort(), nexusBaseURI.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); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); // stateful clients must login first, since other rest urls create no sessions String loginUrl = this.getBaseNexusUrl() + "service/local/authentication/login"; assertThat(executeAndRelease(httpClient, new HttpGet(loginUrl), localcontext), equalTo(200)); // after login check content but make sure only cookie is used httpClient.getCredentialsProvider().clear(); HttpGet getMethod = new HttpGet(url); assertThat(executeAndRelease(httpClient, getMethod, null), equalTo(200)); Cookie sessionCookie = this.getSessionCookie(httpClient.getCookieStore().getCookies()); assertThat("Session Cookie not set", sessionCookie, notNullValue()); httpClient.getCookieStore().clear(); // remove cookies // do not set the cookie, expect failure HttpGet failedGetMethod = new HttpGet(url); assertThat(executeAndRelease(httpClient, failedGetMethod, null), equalTo(401)); // set the cookie expect a 200, If a cookie is set, and cannot be found on the server, the response will fail // with a 401 httpClient.getCookieStore().addCookie(sessionCookie); getMethod = new HttpGet(url); assertThat(executeAndRelease(httpClient, getMethod, null), equalTo(200)); }
From source file:fx.browser.Window.java
public void setLocation(String location) throws URISyntaxException { System.out.println("# " + this.toString() + "-Classloader: " + getClass().getClassLoader().toString() + " setLocation()"); this.location = location; HttpGet httpGet = new HttpGet(new URI(location)); try (CloseableHttpResponse response = Browser.getHttpClient().execute(httpGet)) { switch (response.getStatusLine().getStatusCode()) { case HttpStatus.SC_OK: FXMLLoader loader = new FXMLLoader(); Header header = response.getFirstHeader("class-loader-url"); if (header != null) { URL url = new URL(location); url = new URL(url.getProtocol(), url.getHost(), url.getPort(), header.getValue()); if (logger.isLoggable(Level.INFO)) { logger.log(Level.INFO, "Set up remote classloader: {0}", url); }//from w ww . j av a 2s . c o m loader.setClassLoader(HttpClassLoader.getInstance(url, getClass().getClassLoader())); } try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); response.getEntity().writeTo(buffer); response.close(); setContent(loader.load(new ByteArrayInputStream(buffer.toByteArray()))); } catch (Exception e) { response.close(); logger.log(Level.INFO, e.toString(), e); Node node = loader.load(getClass().getResourceAsStream("/fxml/webview.fxml")); WebViewController controller = (WebViewController) loader.getController(); controller.view(location); setContent(node); } break; case HttpStatus.SC_UNAUTHORIZED: response.close(); Optional<Pair<String, String>> result = new LoginDialog().showAndWait(); if (result.isPresent()) { URL url = new URL(location); Browser.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), new UsernamePasswordCredentials(result.get().getKey(), result.get().getValue())); setLocation(location); } break; } } catch (IOException e) { e.printStackTrace(); } }
From source file:com.amalto.workbench.utils.HttpClientUtil.java
private static DefaultHttpClient wrapAuthClient(String url, String username, String password) throws SecurityException { DefaultHttpClient client = createClient(); URI uri = URI.create(url); AuthScope authScope = new AuthScope(uri.getHost(), uri.getPort()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); client.getCredentialsProvider().setCredentials(authScope, credentials); return client; }
From source file:org.apache.solr.client.solrj.impl.HttpClientUtilTest.java
@Test public void testSetParams() { ModifiableSolrParams params = new ModifiableSolrParams(); params.set(HttpClientUtil.PROP_ALLOW_COMPRESSION, true); params.set(HttpClientUtil.PROP_BASIC_AUTH_PASS, "pass"); params.set(HttpClientUtil.PROP_BASIC_AUTH_USER, "user"); params.set(HttpClientUtil.PROP_CONNECTION_TIMEOUT, 12345); params.set(HttpClientUtil.PROP_FOLLOW_REDIRECTS, true); params.set(HttpClientUtil.PROP_MAX_CONNECTIONS, 22345); params.set(HttpClientUtil.PROP_MAX_CONNECTIONS_PER_HOST, 32345); params.set(HttpClientUtil.PROP_SO_TIMEOUT, 42345); params.set(HttpClientUtil.PROP_USE_RETRY, false); DefaultHttpClient client = (DefaultHttpClient) HttpClientUtil.createClient(params); try {/*www. j ava2 s . c o m*/ assertEquals(12345, HttpConnectionParams.getConnectionTimeout(client.getParams())); assertEquals(PoolingClientConnectionManager.class, client.getConnectionManager().getClass()); assertEquals(22345, ((PoolingClientConnectionManager) client.getConnectionManager()).getMaxTotal()); assertEquals(32345, ((PoolingClientConnectionManager) client.getConnectionManager()).getDefaultMaxPerRoute()); assertEquals(42345, HttpConnectionParams.getSoTimeout(client.getParams())); assertEquals(HttpClientUtil.NO_RETRY, client.getHttpRequestRetryHandler()); assertEquals("pass", client.getCredentialsProvider().getCredentials(new AuthScope("127.0.0.1", 1234)).getPassword()); assertEquals("user", client.getCredentialsProvider().getCredentials(new AuthScope("127.0.0.1", 1234)) .getUserPrincipal().getName()); assertEquals(true, client.getParams().getParameter(ClientPNames.HANDLE_REDIRECTS)); } finally { client.close(); } }
From source file:pl.wavesoftware.wfirma.api.simple.mapper.SimpleGateway.java
private String get(@Nonnull HttpRequest httpRequest) throws WFirmaException { httpRequest.setHeader("Accept", "text/xml"); HttpHost target = getTargetHost();// w w w.j a va 2 s . c om CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(credentials.getConsumerKey(), credentials.getConsumerSecret())); try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider) .build()) { // 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); try (CloseableHttpResponse response = httpclient.execute(target, httpRequest, localContext)) { return getContent(response); } } catch (IOException ioe) { throw new RemoteGatewayException(ioe); } }
From source file:com.sonymobile.tools.gerrit.gerritevents.workers.rest.AbstractRestCommandJob.java
@Override public void run() { ReviewInput reviewInput = createReview(); String reviewEndpoint = resolveEndpointURL(); HttpPost httpPost = createHttpPostEntity(reviewInput, reviewEndpoint); if (httpPost == null) { return;/*from www. j av a2s. com*/ } DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), config.getHttpCredentials()); if (config.getGerritProxy() != null && !config.getGerritProxy().isEmpty()) { try { URL url = new URL(config.getGerritProxy()); HttpHost proxy = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } catch (MalformedURLException e) { logger.error("Could not parse proxy URL, attempting without proxy.", e); if (altLogger != null) { altLogger.print("ERROR Could not parse proxy URL, attempting without proxy. " + e.getMessage()); } } } try { HttpResponse httpResponse = httpclient.execute(httpPost); String response = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8"); if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { logger.error("Gerrit response: {}", httpResponse.getStatusLine().getReasonPhrase()); if (altLogger != null) { altLogger.print("ERROR Gerrit response: " + httpResponse.getStatusLine().getReasonPhrase()); } } } catch (Exception e) { logger.error("Failed to submit result to Gerrit", e); if (altLogger != null) { altLogger.print("ERROR Failed to submit result to Gerrit" + e.toString()); } } }
From source file:net.nightwhistler.pageturner.PageTurnerModule.java
/** * Binds the HttpClient interface to the DefaultHttpClient implementation. * /*from w w w . j a va 2s .c o m*/ * In testing we'll use a stub. * * @return */ @Provides @Inject public HttpClient getHttpClient(Configuration config) { HttpParams httpParams = new BasicHttpParams(); DefaultHttpClient client; if (config.isAcceptSelfSignedCertificates()) { client = new SSLHttpClient(httpParams); } else { client = new DefaultHttpClient(httpParams); } for (CustomOPDSSite site : config.getCustomOPDSSites()) { if (site.getUserName() != null && site.getUserName().length() > 0) { try { URL url = new URL(site.getUrl()); client.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), new UsernamePasswordCredentials(site.getUserName(), site.getPassword())); } catch (MalformedURLException mal) { //skip to the next } } } return client; }
From source file:org.jbpm.workbench.wi.backend.server.casemgmt.service.CaseProvisioningExecutor.java
protected int getManagementInterfaceStatus(String host, String managementPort, String password, String username) {// www . j a v a 2s .c om final CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(new AuthScope(host, Integer.valueOf(managementPort)), new UsernamePasswordCredentials(username, password)); try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider) .build()) { final HttpGet httpget = new HttpGet("http://" + host + ":" + managementPort + "/management"); return httpClient.execute(httpget).getStatusLine().getStatusCode(); } catch (Exception ex) { LOGGER.error("Exception while trying to connect to Wildfly Management interface", ex); return -1; } }