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.hyperic.hq.hqapi1.HQConnection.java
private <T> T runMethod(HttpRequestBase method, String uri, ResponseHandler<T> responseHandler) throws IOException { String protocol = _isSecure ? "https" : "http"; ServiceError error;//from ww w . j a v a 2 s.c om URL url = new URL(protocol, _host, _port, uri); try { method.setURI(url.toURI()); } catch (URISyntaxException e) { throw new IllegalArgumentException("The syntax of request url [" + uri + "] is invalid", e); } _log.debug("Setting URI: " + url.toString()); DefaultHttpClient client = new DefaultHttpClient(); if (_isSecure) { // To allow for self signed certificates configureSSL(client); } // Validate user & password inputs if (_user == null || _user.length() == 0) { error = new ServiceError(); error.setErrorCode("LoginFailure"); error.setReasonText("User name cannot be null or empty"); return responseHandler.getErrorResponse(error); } if (_password == null || _password.length() == 0) { error = new ServiceError(); error.setErrorCode("LoginFailure"); error.setReasonText("Password cannot be null or empty"); return responseHandler.getErrorResponse(error); } // Set Basic auth creds UsernamePasswordCredentials defaultcreds = new UsernamePasswordCredentials(_user, _password); client.getCredentialsProvider().setCredentials(AuthScope.ANY, defaultcreds); // Preemptive authentication AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); HttpHost host = new HttpHost(_host, _port, protocol); authCache.put(host, basicAuth); BasicHttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.AUTH_CACHE, authCache); method.getParams().setParameter(ClientPNames.HANDLE_AUTHENTICATION, true); // Disable re-tries client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, true)); HttpResponse response = client.execute(method, localContext); return responseHandler.handleResponse(response); }
From source file:org.mitre.dsmiley.httpproxy.ProxyServlet.java
/** * Called from {@link #init(javax.servlet.ServletConfig)}. HttpClient offers * many opportunities for customization. By default, <a href= * "http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/SystemDefaultHttpClient.html"> * SystemDefaultHttpClient</a> is used if available, otherwise it falls back * to:/*from www . jav a 2 s.c o m*/ * * <pre> * new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams) * </pre> * * SystemDefaultHttpClient uses PoolingClientConnectionManager. In any case, * it should be thread-safe. */ protected HttpClient createHttpClient(HttpParams hcParams) { try { String negotiateURL = getConfigParam("negotiate.url"); String negotiateSPN = getConfigParam("negotiate.spn"); if (negotiateURL != null && negotiateSPN != null) { System.out.println("negotiate url:" + negotiateURL); System.out.println("negotiate spn:" + negotiateSPN); // initialize the Windows security Context to get the negotiate // client token IWindowsSecurityContext clientContext = null; IWindowsCredentialsHandle clientCredentials = null; clientContext = WindowsSecurityContextImpl.getCurrent(SECURITY_PACKAGE, negotiateSPN); clientCredentials = WindowsCredentialsHandleImpl.getCurrent(SECURITY_PACKAGE); clientCredentials.initialize(); String username = WindowsAccountImpl.getCurrentUsername(); System.out.println("credentials for user " + username + " get prepared"); byte[] token = clientContext.getToken(); // encode the token with Base64 to be able to add it to the http // header String clientToken = Base64.encodeBase64String(token); System.out.println("clientToken" + clientToken); // if there is only a negotiate url the rest of the // authorization is based on cookies // so we need to support them. CookieStore cookieStore = new BasicCookieStore(); RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build(); HttpClientContext context = HttpClientContext.create(); proxyContext = context; context.setCookieStore(cookieStore); HttpClient httpClient = HttpClients.custom().disableRedirectHandling() .setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).build(); // first we need to act as a normal browser to get a http 401 // with negotiate header doActAsBrowser = true; HttpGet browserHttpGet = new HttpGet(negotiateURL); addBrowserHeader(browserHttpGet); HttpResponse rep = httpClient.execute(browserHttpGet, context); if (rep.getStatusLine().getStatusCode() == 401) { System.out.println("negotiate requested - sending negotiate client token"); HttpGet negotiateHttpGet = new HttpGet(negotiateURL); addBrowserHeader(negotiateHttpGet); negotiateHttpGet.addHeader("Authorization", "Negotiate " + clientToken); HttpResponse response = httpClient.execute(negotiateHttpGet, context); System.out.println( "http result code of negotiate request:" + response.getStatusLine().getStatusCode()); // now the url needs to be called periodically to keep the // cookie and connection alive String refreshTimeString = getConfigParam("negotiate.refreshtime"); long refreshTime = 1000000; if (refreshTimeString != null) { refreshTime = Long.parseLong(refreshTimeString); } HttpClientRefreshThread thread = new HttpClientRefreshThread(refreshTime, negotiateURL); thread.start(); List<org.apache.http.cookie.Cookie> cookies = context.getCookieStore().getCookies(); cookieString = ""; int size = cookies.size() - 1; for (int i = 0; i < cookies.size(); i++) { cookieString += cookies.get(i).getName(); cookieString += "="; cookieString += cookies.get(i).getValue(); if (i != size) cookieString += "; "; } } else { System.out.println("No negotiate requested"); } } else { if (!WinHttpClients.isWinAuthAvailable()) { System.out.println("Integrated Win auth is not supported!!!"); } else { HttpClientBuilder builder = WinHttpClients.custom(); Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.BASIC, new BasicSchemeFactory()) .register(AuthSchemes.DIGEST, new DigestSchemeFactory()) .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()) .register(AuthSchemes.NTLM, new NTLMSchemeFactory()) .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build(); builder.setDefaultAuthSchemeRegistry(authSchemeRegistry); String username = getConfigParam("user"); String password = getConfigParam("password"); String domain = getConfigParam("domain"); String host = getConfigParam("host"); if (username != null) { NTCredentials cred = new NTCredentials(username, password, host, domain); CredentialsProvider credsProvider = new WindowsCredentialsProvider( new SystemDefaultCredentialsProvider()); credsProvider.setCredentials(AuthScope.ANY, cred); builder.setDefaultCredentialsProvider(credsProvider); } builder.disableCookieManagement(); builder.disableRedirectHandling(); return builder.build(); } // as of HttpComponents v4.2, this class is better since it uses // System // Properties: Class<?> clientClazz = Class.forName("org.apache.http.impl.client.SystemDefaultHttpClient"); Constructor<?> constructor = clientClazz.getConstructor(HttpParams.class); return (HttpClient) constructor.newInstance(hcParams); } } catch (ClassNotFoundException e) { // no problem; use v4.1 below } catch (Exception e) { throw new RuntimeException(e); } // Fallback on using older client: return new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams); }
From source file:org.opencastproject.kernel.security.TrustedHttpClientImpl.java
@Override public HttpResponse execute(HttpUriRequest httpUriRequest, int connectionTimeout, int socketTimeout) throws TrustedHttpClientException { HttpClient httpClient = makeHttpClient(); httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); // Add the request header to elicit a digest auth response httpUriRequest.setHeader(REQUESTED_AUTH_HEADER, DIGEST_AUTH); httpUriRequest.setHeader(SecurityConstants.AUTHORIZATION_HEADER, "true"); if (serviceRegistry != null && serviceRegistry.getCurrentJob() != null) httpUriRequest.setHeader(CURRENT_JOB_HEADER, Long.toString(serviceRegistry.getCurrentJob().getId())); // If a security service has been set, use it to pass the current security context on logger.debug("Adding security context to request"); Organization organization = securityService.getOrganization(); if (organization != null) { httpUriRequest.setHeader(SecurityConstants.ORGANIZATION_HEADER, organization.getId()); User currentUser = securityService.getUser(); if (currentUser != null) httpUriRequest.setHeader(SecurityConstants.USER_HEADER, currentUser.getUserName()); }//w w w .j a v a2 s .c om if ("GET".equalsIgnoreCase(httpUriRequest.getMethod()) || "HEAD".equalsIgnoreCase(httpUriRequest.getMethod())) { // Set the user/pass UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds); // Run the request (the http client handles the multiple back-and-forth requests) HttpResponse response = null; try { response = httpClient.execute(httpUriRequest); responseMap.put(response, httpClient); return response; } catch (IOException e) { // close the http connection(s) httpClient.getConnectionManager().shutdown(); throw new TrustedHttpClientException(e); } } // HttpClient doesn't handle the request dynamics for other verbs (especially when sending a streamed multipart // request), so we need to handle the details of the digest auth back-and-forth manually manuallyHandleDigestAuthentication(httpUriRequest, httpClient); HttpResponse response = null; try { response = httpClient.execute(httpUriRequest); if (nonceTimeoutRetries > 0 && hadNonceTimeoutResponse(response)) { httpClient.getConnectionManager().shutdown(); response = retryAuthAndRequestAfterNonceTimeout(httpUriRequest, response); } responseMap.put(response, httpClient); return response; } catch (Exception e) { // if we have a response, remove it from the map if (response != null) { responseMap.remove(response); } // close the http connection(s) httpClient.getConnectionManager().shutdown(); throw new TrustedHttpClientException(e); } }
From source file:org.opennms.core.web.HttpClientWrapper.java
protected void setCredentials(final HttpClientBuilder httpClientBuilder, final String username, final String password) { final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, credentials); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); }
From source file:org.springframework.data.solr.server.support.HttpSolrClientFactory.java
private void appendAuthentication(Credentials credentials, String authPolicy, SolrClient solrClient) { if (isHttpSolrClient(solrClient)) { HttpSolrClient httpSolrClient = (HttpSolrClient) solrClient; if (credentials != null && StringUtils.isNotBlank(authPolicy) && assertHttpClientInstance(httpSolrClient.getHttpClient())) { AbstractHttpClient httpClient = (AbstractHttpClient) httpSolrClient.getHttpClient(); httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials); httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, Collections.singletonList(authPolicy)); }/*w w w. ja v a 2 s .co m*/ } }
From source file:org.whitesource.agent.client.WssServiceClientImpl.java
@Override public void setProxy(String host, int port, String username, String password) { if (host == null || host.trim().length() == 0) { return;//from www . j a v a 2 s. c o m } if (port < 0 || port > 65535) { return; } HttpHost proxy = new HttpHost(host, port); // httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); httpClient = HttpClients.custom().setRoutePlanner(routePlanner).build(); logger.info("Using proxy: " + proxy.toHostString()); if (username != null && username.trim().length() > 0) { logger.info("Proxy username: " + username); Credentials credentials; if (username.indexOf('/') >= 0) { credentials = new NTCredentials(username + ":" + password); } else if (username.indexOf('\\') >= 0) { username = username.replace('\\', '/'); credentials = new NTCredentials(username + ":" + password); } else { credentials = new UsernamePasswordCredentials(username, password); } CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, credentials); // TODO check httpClient = HttpClientBuilder.create().setProxy(proxy).setDefaultCredentialsProvider(credsProvider) .build(); // httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); } }
From source file:org.xwiki.extension.repository.http.internal.DefaultHttpClientFactory.java
@Override public HttpClientBuilder createHttpClientBuilder(String user, String password) { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // Pre-configure with everything configured at JVM level httpClientBuilder.useSystemProperties(); // Setup user agent httpClientBuilder.setUserAgent(this.configuration.getUserAgent()); // Setup authentication if (user != null) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password)); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); }/*from w w w . j a v a2 s . com*/ return httpClientBuilder; }
From source file:test.com.xceptance.xlt.common.actions.LWSimpleURLTest.java
/********************************************************************************** * Check setting of credentials// w ww . j av a 2 s. com * * @throws IOException *********************************************************************************/ @Test public void testCredentials_Set() throws IOException { final List<AbstractLightWeightPageAction> actions = mockIt(login, password, "URL", "{url}"); final Credentials creds = actions.get(0).getWebClient().getCredentialsProvider() .getCredentials(AuthScope.ANY); Assert.assertEquals("Login does not match.", login, creds.getUserPrincipal().getName()); Assert.assertEquals("Password does not match.", password, creds.getPassword()); }
From source file:test.com.xceptance.xlt.common.actions.LWSimpleURLTest.java
@Test public void testCredentials_NotSet() throws IOException { final List<AbstractLightWeightPageAction> actions = mockIt(null, null, "URL", "{url}"); final Credentials creds = actions.get(0).getWebClient().getCredentialsProvider() .getCredentials(AuthScope.ANY); Assert.assertNull("There is an credential provider set.", creds); }
From source file:test.com.xceptance.xlt.common.actions.SimpleURLTest.java
/********************************************************************************** * Check setting of credentials//from ww w. ja v a 2 s .c o m * * @throws IOException *********************************************************************************/ @Test public void testCredentials_Set() throws IOException { final List<AbstractHtmlPageAction> actions = mockIt(login, password, "URL", "{url}"); final Credentials creds = actions.get(0).getWebClient().getCredentialsProvider() .getCredentials(AuthScope.ANY); Assert.assertEquals("Login does not match.", login, creds.getUserPrincipal().getName()); Assert.assertEquals("Password does not match.", password, creds.getPassword()); }