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.ops4j.pax.web.itest.DigestAuthenticationTest.java
@Test public void shouldPermitAccessToUnprotectedResource() throws Exception { assertThat(servletContext.getContextPath(), is("/digest")); String path = String.format("http://localhost:%d/digest/plain.txt", getHttpPort()); HttpClientContext context = HttpClientContext.create(); BasicCredentialsProvider cp = new BasicCredentialsProvider(); cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("mustermann", "wrong")); CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(cp).build(); HttpGet httpGet = new HttpGet(path); HttpResponse response = client.execute(httpGet, context); int statusCode = response.getStatusLine().getStatusCode(); assertThat(statusCode, is(200));//from w ww .j ava 2 s . c om String text = EntityUtils.toString(response.getEntity()); assertThat(text, containsString("plain text")); }
From source file:com.ericsson.gerrit.plugins.highavailability.forwarder.rest.HttpClientProvider.java
private BasicCredentialsProvider buildCredentials() { BasicCredentialsProvider creds = new BasicCredentialsProvider(); creds.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(cfg.http().user(), cfg.http().password())); return creds; }
From source file:org.elasticsearch.client.RestClientSingleHostIntegTests.java
private static RestClient createRestClient(final boolean useAuth, final boolean usePreemptiveAuth) { // provide the username/password for every request final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user", "pass")); final RestClientBuilder restClientBuilder = RestClient .builder(new HttpHost(httpServer.getAddress().getHostString(), httpServer.getAddress().getPort())) .setDefaultHeaders(defaultHeaders); if (pathPrefix.length() > 0) { // sometimes cut off the leading slash restClientBuilder.setPathPrefix(randomBoolean() ? pathPrefix.substring(1) : pathPrefix); }//from w ww . j a v a 2s .co m if (useAuth) { restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient(final HttpAsyncClientBuilder httpClientBuilder) { if (usePreemptiveAuth == false) { // disable preemptive auth by ignoring any authcache httpClientBuilder.disableAuthCaching(); } return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } }); } return restClientBuilder.build(); }
From source file:org.sonatype.nexus.examples.url.UrlRealmTest.java
@Test public void testAuthc() throws Exception { // build client BasicCredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); when(hc4Provider.createHttpClient(Mockito.any(RemoteStorageContext.class))).thenReturn(httpClient); final AuthenticationInfo info = urlRealm .getAuthenticationInfo(new UsernamePasswordToken(username, password)); assertThat(info, notNullValue());// w w w . j av a 2s .co m }
From source file:org.apache.brooklyn.security.StockSecurityProviderTest.java
private void checkRestSecurity(String username, String password, final int code) throws IOException { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); if (username != null && password != null) { credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); }//from w w w . j av a 2s. co m try (CloseableHttpClient client = HttpClientBuilder.create() .setDefaultCredentialsProvider(credentialsProvider).build()) { Asserts.succeedsEventually(new Callable<Void>() { @Override public Void call() throws Exception { assertResponseEquals(client, code); return null; } }); } }
From source file:org.apache.sling.tests.sling_2998.SLING_2998_IT.java
@Test public void testSlingTest() throws Exception { final HttpClient httpClient = HttpClients.createDefault(); final HttpGet httpGet = new HttpGet(baseUri() + "/sling-test/sling/sling-test.html"); final HttpResponse httpResponse = httpClient.execute(httpGet); assertEquals(200, httpResponse.getStatusLine().getStatusCode()); final Dictionary<String, String> properties = new Hashtable<String, String>(); properties.put("sling.auth.requirements", "+/sling-test"); bundleContext.registerService(Object.class.getName(), new Object(), properties); final HttpResponse httpResponseUnauthorized = httpClient.execute(httpGet); assertEquals(401, httpResponseUnauthorized.getStatusLine().getStatusCode()); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin")); final HttpClient authenticatingHttpClient = HttpClients.custom() .setDefaultCredentialsProvider(credentialsProvider).build(); final HttpResponse httpResponseAuthorized = authenticatingHttpClient.execute(httpGet); assertEquals(200, httpResponseAuthorized.getStatusLine().getStatusCode()); }
From source file:com.platts.portlet.documentlibrary.DLSetSeoUrl.java
@Override public void processAction(StrutsPortletAction originalStrutsPortletAction, PortletConfig portletConfig, ActionRequest actionRequest, ActionResponse actionResponse) throws PortalException, SystemException, IOException { LOGGER.info("the process action for struts action DLSetSeoUrl is getting called"); String uri = ParamUtil.getString(actionRequest, "uri", null); String seoURL = ParamUtil.getString(actionRequest, "seoURL", null); Long fileEntryId = ParamUtil.getLong(actionRequest, "fileEntryId"); LOGGER.info("uri is " + uri + " seourl is " + seoURL + " fileEntryId " + fileEntryId); FileEntry fileEntry = DLAppLocalServiceUtil.getFileEntry(fileEntryId); // sample url http://10.206.111.1:8030/v1/resources/content?uri=/test/holiday.xml&seoUrl=/EditorBios/regina1233johnson.xml StringBuilder url = new StringBuilder("http://10.206.111.1:8030/v1/resources/content?uri="); url.append(uri).append(StringPool.SLASH).append(fileEntry.getTitle()).append("&seoUrl=").append(seoURL); LOGGER.info("the url is " + url.toString()); PlattsExportUtil exportUtil = new PlattsExportUtil(); ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY); File file = exportUtil.getFileFromDLFile(themeDisplay.getUserId(), fileEntry.getFileEntryId(), fileEntry.getLatestFileVersion().getVersion()); //LOGGER.info("the file is " + FileUtils.readFileToString(file)); FileEntity fileEntity = new FileEntity(file); fileEntity.setContentType("application/xml"); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("CPUser", "CPUser22"); credentialsProvider.setCredentials(AuthScope.ANY, credentials); CloseableHttpClient httpClient = HttpClientBuilder.create() .setDefaultCredentialsProvider(credentialsProvider).build(); HttpPost postRequest = new HttpPost(url.toString()); postRequest.setEntity(fileEntity);/*from w w w .j a v a 2 s .co m*/ try { CloseableHttpResponse response = httpClient.execute(postRequest); HttpEntity entity = response.getEntity(); String responseString = EntityUtils.toString(entity); Document document = SAXReaderUtil.read(responseString); String responseText = document.getRootElement().selectSingleNode("/response").getText(); if (responseText.equalsIgnoreCase("ok")) { SessionMessages.add(actionRequest, "seoURLActionSuccess"); hideDefaultSuccessMessage(actionRequest); String redirect = PortalUtil.escapeRedirect(ParamUtil.getString(actionRequest, "redirect")); try { actionResponse.sendRedirect(redirect); } catch (IOException e) { LOGGER.error("error redirecting ", e); } } else { SessionErrors.add(actionRequest, "seoURLActionFailure"); LOGGER.info("the error text is " + responseText); actionResponse.setRenderParameter("errorMessage", responseText); } response.close(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } }
From source file:sachin.spider.WebSpider.java
/** * * @param config/*from w w w . j a v a 2s . c o m*/ * @param latch */ @SuppressWarnings("deprecation") public void setValues(SpiderConfig config, CountDownLatch latch) { try { this.config = config; this.latch = latch; HttpClientBuilder builder = HttpClientBuilder.create(); builder.setUserAgent(config.getUserAgentString()); SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(java.security.cert.X509Certificate[] xcs, String string) throws java.security.cert.CertificateException { return true; } }).build(); builder.setSslcontext(sslContext); HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslSocketFactory).build(); cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry); cm.setDefaultMaxPerRoute(config.getTotalSpiders() * 2); cm.setMaxTotal(config.getTotalSpiders() * 2); if (config.isAuthenticate()) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(config.getUsername(), config.getPassword())); httpclient = HttpClients.custom().setUserAgent(config.getUserAgentString()) .setDefaultCredentialsProvider(credentialsProvider).setConnectionManager(cm).build(); } else { httpclient = HttpClients.custom().setConnectionManager(cm).setUserAgent(config.getUserAgentString()) .build(); } } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) { Logger.getLogger(WebSpider.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.valkyriercp.security.remoting.BasicAuthCommonsHttpInvokerProxyFactoryBean.java
/** * Handle a change in the current authentication token. * This method will fail fast if the executor isn't a CommonsHttpInvokerRequestExecutor. * @see org.valkyriercp.security.AuthenticationAware#setAuthenticationToken(org.springframework.security.core.Authentication) *///w ww . j a v a 2s. com public void setAuthenticationToken(Authentication authentication) { if (logger.isDebugEnabled()) { logger.debug("New authentication token: " + authentication); } HttpComponentsHttpInvokerRequestExecutor executor = (HttpComponentsHttpInvokerRequestExecutor) getHttpInvokerRequestExecutor(); DefaultHttpClient httpClient = (DefaultHttpClient) executor.getHttpClient(); BasicCredentialsProvider provider = new BasicCredentialsProvider(); httpClient.setCredentialsProvider(provider); httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor()); UsernamePasswordCredentials usernamePasswordCredentials; if (authentication != null) { usernamePasswordCredentials = new UsernamePasswordCredentials(authentication.getName(), authentication.getCredentials().toString()); } else { usernamePasswordCredentials = null; } provider.setCredentials(AuthScope.ANY, usernamePasswordCredentials); }