List of usage examples for org.apache.http.impl.client BasicCredentialsProvider setCredentials
public void setCredentials(final AuthScope authscope, final Credentials credentials)
From source file:org.opensaml.soap.client.http.AbstractPipelineHttpSOAPClient.java
/** * A convenience method to set a (single) username and password used for BASIC authentication. * To disable BASIC authentication pass null for the credentials instance. * /* ww w . ja v a2s. c o m*/ * <p> * If the <code>authScope</code> is null, an {@link AuthScope} will be generated which specifies * any host, port, scheme and realm. * </p> * * <p>To specify multiple usernames and passwords for multiple host, port, scheme, and realm combinations, instead * provide an instance of {@link CredentialsProvider} via {@link #setCredentialsProvider(CredentialsProvider)}.</p> * * @param credentials the username and password credentials * @param scope the HTTP client auth scope with which to scope the credentials, may be null */ public void setBasicCredentialsWithScope(@Nullable final UsernamePasswordCredentials credentials, @Nullable final AuthScope scope) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); ComponentSupport.ifDestroyedThrowDestroyedComponentException(this); if (credentials != null) { AuthScope authScope = scope; if (authScope == null) { authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT); } BasicCredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(authScope, credentials); setCredentialsProvider(provider); } else { log.debug("Either username or password were null, disabling basic auth"); setCredentialsProvider(null); } }
From source file:org.mumod.util.HttpManager.java
public void setCredentials(String username, String password) { Credentials defaultcreds = new UsernamePasswordCredentials(username, password); String host = AuthScope.ANY_HOST; if (mHost != null) host = mHost;//from w w w . j av a 2 s. com BasicCredentialsProvider cP = new BasicCredentialsProvider(); cP.setCredentials(new AuthScope(host, AuthScope.ANY_PORT, AuthScope.ANY_REALM), defaultcreds); mClient.setCredentialsProvider(cP); mClient.addRequestInterceptor(preemptiveAuth, 0); }
From source file:org.apache.kylin.engine.mr.common.HadoopStatusGetter.java
private String getHttpResponseWithKerberosAuth(String url) throws IOException { String krb5ConfigPath = System.getProperty("java.security.krb5.conf"); if (krb5ConfigPath == null) { krb5ConfigPath = DEFAULT_KRB5_CONFIG_LOCATION; }//from ww w . j a v a 2 s . c o m boolean skipPortAtKerberosDatabaseLookup = true; System.setProperty("java.security.krb5.conf", krb5ConfigPath); System.setProperty("sun.security.krb5.debug", "true"); System.setProperty("javax.security.auth.useSubjectCredsOnly", "false"); DefaultHttpClient client = new DefaultHttpClient(); AuthSchemeRegistry authSchemeRegistry = new AuthSchemeRegistry(); authSchemeRegistry.register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory(skipPortAtKerberosDatabaseLookup)); client.setAuthSchemes(authSchemeRegistry); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); Credentials useJaasCreds = new Credentials() { public String getPassword() { return null; } public Principal getUserPrincipal() { return null; } }; credentialsProvider.setCredentials(new AuthScope(null, -1, null), useJaasCreds); client.setCredentialsProvider(credentialsProvider); String response = null; while (response == null) { if (url.startsWith("https://")) { registerEasyHttps(); } if (url.contains("anonymous=true") == false) { url += url.contains("?") ? "&" : "?"; url += "anonymous=true"; } HttpGet httpget = new HttpGet(url); httpget.addHeader("accept", "application/json"); try { HttpResponse httpResponse = client.execute(httpget); String redirect = null; org.apache.http.Header h = httpResponse.getFirstHeader("Location"); if (h != null) { redirect = h.getValue(); if (isValidURL(redirect) == false) { logger.info("Get invalid redirect url, skip it: " + redirect); Thread.sleep(1000L); continue; } } else { h = httpResponse.getFirstHeader("Refresh"); if (h != null) { String s = h.getValue(); int cut = s.indexOf("url="); if (cut >= 0) { redirect = s.substring(cut + 4); if (isValidURL(redirect) == false) { logger.info("Get invalid redirect url, skip it: " + redirect); Thread.sleep(1000L); continue; } } } } if (redirect == null) { response = IOUtils.toString(httpResponse.getEntity().getContent(), Charset.defaultCharset()); logger.debug("Job " + mrJobId + " get status check result.\n"); } else { url = redirect; logger.debug("Job " + mrJobId + " check redirect url " + url + ".\n"); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error(e.getMessage()); } finally { httpget.releaseConnection(); } } return response; }
From source file:org.opcfoundation.ua.transport.https.HttpsClient.java
/** * Initialize HttpsClient. //from w w w . j a v a 2 s.com * * @param connectUrl * @param tcs */ public void initialize(String connectUrl, TransportChannelSettings tcs, EncoderContext ctx) throws ServiceResultException { this.connectUrl = connectUrl; this.securityPolicyUri = tcs.getDescription().getSecurityPolicyUri(); this.transportChannelSettings = tcs; HttpsSettings httpsSettings = tcs.getHttpsSettings(); HttpsSecurityPolicy[] policies = httpsSettings.getHttpsSecurityPolicies(); if (policies != null && policies.length > 0) securityPolicy = policies[policies.length - 1]; else securityPolicy = HttpsSecurityPolicy.TLS_1_1; // securityPolicy = SecurityPolicy.getSecurityPolicy( this.securityPolicyUri ); if (securityPolicy != HttpsSecurityPolicy.TLS_1_0 && securityPolicy != HttpsSecurityPolicy.TLS_1_1 && securityPolicy != HttpsSecurityPolicy.TLS_1_2) throw new ServiceResultException(StatusCodes.Bad_SecurityChecksFailed, "Https Client doesn't support securityPolicy " + securityPolicy); if (logger.isDebugEnabled()) { logger.debug("initialize: url={}; settings={}", tcs.getDescription().getEndpointUrl(), ObjectUtils.printFields(tcs)); } // Setup Encoder EndpointConfiguration endpointConfiguration = tcs.getConfiguration(); encoderCtx = ctx; encoderCtx.setMaxArrayLength( endpointConfiguration.getMaxArrayLength() != null ? endpointConfiguration.getMaxArrayLength() : 0); encoderCtx.setMaxStringLength( endpointConfiguration.getMaxStringLength() != null ? endpointConfiguration.getMaxStringLength() : 0); encoderCtx.setMaxByteStringLength(endpointConfiguration.getMaxByteStringLength() != null ? endpointConfiguration.getMaxByteStringLength() : 0); encoderCtx.setMaxMessageSize( endpointConfiguration.getMaxMessageSize() != null ? endpointConfiguration.getMaxMessageSize() : 0); timer = TimerUtil.getTimer(); try { SchemeRegistry sr = new SchemeRegistry(); if (protocol.equals(UriUtil.SCHEME_HTTPS)) { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(httpsSettings.getKeyManagers(), httpsSettings.getTrustManagers(), null); X509HostnameVerifier hostnameVerifier = httpsSettings.getHostnameVerifier() != null ? httpsSettings.getHostnameVerifier() : SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; SSLSocketFactory sf = new SSLSocketFactory(sslcontext, hostnameVerifier) { protected void prepareSocket(javax.net.ssl.SSLSocket socket) throws IOException { socket.setEnabledCipherSuites(cipherSuites); }; }; SSLEngine sslEngine = sslcontext.createSSLEngine(); String[] enabledCipherSuites = sslEngine.getEnabledCipherSuites(); cipherSuites = CryptoUtil.filterCipherSuiteList(enabledCipherSuites, securityPolicy.getCipherSuites()); logger.info("Enabled protocols in SSL Engine are {}", Arrays.toString(sslEngine.getEnabledProtocols())); logger.info("Enabled CipherSuites in SSL Engine are {}", Arrays.toString(enabledCipherSuites)); logger.info("Client CipherSuite selection for {} is {}", securityPolicy.getPolicyUri(), Arrays.toString(cipherSuites)); Scheme https = new Scheme("https", 443, sf); sr.register(https); } if (protocol.equals(UriUtil.SCHEME_HTTP)) { Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory()); sr.register(http); } if (ccm == null) { PoolingClientConnectionManager pccm = new PoolingClientConnectionManager(sr); ccm = pccm; pccm.setMaxTotal(maxConnections); pccm.setDefaultMaxPerRoute(maxConnections); } BasicHttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, transportChannelSettings.getConfiguration().getOperationTimeout()); HttpConnectionParams.setSoTimeout(httpParams, 0); httpclient = new DefaultHttpClient(ccm, httpParams); // Set username and password authentication if (httpsSettings.getUsername() != null && httpsSettings.getPassword() != null) { BasicCredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(httpsSettings.getUsername(), httpsSettings.getPassword())); httpclient.setCredentialsProvider(credsProvider); } } catch (NoSuchAlgorithmException e) { new ServiceResultException(e); } catch (KeyManagementException e) { new ServiceResultException(e); } }
From source file:net.sf.jasperreports.data.http.HttpDataService.java
protected void setAuthentication(Map<String, Object> parameters, HttpClientBuilder clientBuilder) { String username = getUsername(parameters); if (username != null) { String password = getPassword(parameters); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); //FIXME proxy authentication? credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password)); clientBuilder.setDefaultCredentialsProvider(credentialsProvider); }/*from w w w . j a v a2 s . c o m*/ }
From source file:com.heneryh.aquanotes.io.ApexExecutor.java
public void updateOutlet(Cursor cursor, String outletName, int position) throws HandlerException { /**//from w ww .j a v a 2 s . c om * The cursor contains all of the controller details. */ String lanUri = cursor.getString(ControllersQuery.LAN_URL); String wanUri = cursor.getString(ControllersQuery.WAN_URL); String user = cursor.getString(ControllersQuery.USER); String pw = cursor.getString(ControllersQuery.PW); String ssid = cursor.getString(ControllersQuery.WIFI_SSID); String model = cursor.getString(ControllersQuery.MODEL); // Uhg, WifiManager stuff below crashes in AVD if wifi not enabled so first we have to check if on wifi ConnectivityManager cm = (ConnectivityManager) mActContext.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo nInfo = cm.getActiveNetworkInfo(); String apexBaseURL; if (nInfo.getType() == ConnectivityManager.TYPE_WIFI) { // Get the currently connected SSID, if it matches the 'Home' one then use the local WiFi URL rather than the public one WifiManager wm = (WifiManager) mActContext.getSystemService(Context.WIFI_SERVICE); WifiInfo wInfo = wm.getConnectionInfo(); // somewhere read this was a quoted string but appears not to be if (wInfo.getSSID().equalsIgnoreCase(ssid)) { // the ssid will be quoted in the info class apexBaseURL = lanUri; } else { apexBaseURL = wanUri; } } else { apexBaseURL = wanUri; } // for this function we need to append to the URL. I should really // check if the "/" was put on the end by the user here to avoid // possible errors. if (!apexBaseURL.endsWith("/")) { String tmp = apexBaseURL + "/"; apexBaseURL = tmp; } // oh, we should also check if it starts with an "http://" if (!apexBaseURL.toLowerCase().startsWith("http://")) { String tmp = "http://" + apexBaseURL; apexBaseURL = tmp; } // oh, we should also check if it ends with an "status.sht" on the end and remove it. // This used to be common for both the Apex and ACiii but during // the 4.04 beta Apex release it seemed to have broke and forced // me to use status.sht for the Apex. Maybe it was fixed but I // haven't checked it. // edit - this was not needed for the longest while but now that we are pushing just one // outlet, the different methods seem to be needed again. Really not sure why. String apexURL; if (model.equalsIgnoreCase("AC4")) { apexURL = apexBaseURL + "status.sht"; } else { apexURL = apexBaseURL + "cgi-bin/status.cgi"; } //Create credentials for basic auth // create a basic credentials provider and pass the credentials // Set credentials provider for our default http client so it will use those credentials UsernamePasswordCredentials c = new UsernamePasswordCredentials(user, pw); BasicCredentialsProvider cP = new BasicCredentialsProvider(); cP.setCredentials(AuthScope.ANY, c); ((DefaultHttpClient) mHttpClient).setCredentialsProvider(cP); // Build the POST update which looks like this: // form="status" // method="post" // action="status.sht" // // name="T5s_state", value="0" (0=Auto, 1=Man Off, 2=Man On) // submit -> name="Update", value="Update" // -- or // name="FeedSel", value="0" (0=A, 1=B) // submit -> name="FeedCycle", value="Feed" // -- or // submit -> name="FeedCycle", value="Feed Cancel" HttpPost httppost = new HttpPost(apexURL); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); // Add your data nameValuePairs.add(new BasicNameValuePair("name", "status")); nameValuePairs.add(new BasicNameValuePair("method", "post")); if (model.equalsIgnoreCase("AC4")) { nameValuePairs.add(new BasicNameValuePair("action", "status.sht")); } else { nameValuePairs.add(new BasicNameValuePair("action", "/cgi-bin/status.cgi")); } String pendingStateS = String.valueOf(position); nameValuePairs.add(new BasicNameValuePair(outletName + "_state", pendingStateS)); nameValuePairs.add(new BasicNameValuePair("Update", "Update")); try { httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse resp = mHttpClient.execute(httppost); final int status = resp.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { throw new HandlerException( "Unexpected server response " + resp.getStatusLine() + " for " + httppost.getRequestLine()); } } catch (HandlerException e) { throw e; } catch (ClientProtocolException e) { throw new HandlerException("Problem reading remote response for " + httppost.getRequestLine(), e); } catch (IOException e) { throw new HandlerException("Problem reading remote response for " + httppost.getRequestLine(), e); } }
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) *///from ww w . j a va2s. c om 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); }
From source file:com.heneryh.aquanotes.io.ApexExecutor.java
public void feedCycle(Cursor cursor, int cycleNumber) throws HandlerException { /**/*w w w . j a v a 2 s.c o m*/ * The cursor contains all of the controller details. */ String lanUri = cursor.getString(ControllersQuery.LAN_URL); String wanUri = cursor.getString(ControllersQuery.WAN_URL); String user = cursor.getString(ControllersQuery.USER); String pw = cursor.getString(ControllersQuery.PW); String ssid = cursor.getString(ControllersQuery.WIFI_SSID); String model = cursor.getString(ControllersQuery.MODEL); String apexBaseURL; // Determine if we are on the LAN or WAN and then use appropriate URL // Uhg, WifiManager stuff below crashes if wifi not enabled so first we have to check if on wifi ConnectivityManager cm = (ConnectivityManager) mActContext.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo nInfo = cm.getActiveNetworkInfo(); if (nInfo.getType() == ConnectivityManager.TYPE_WIFI) { // Get the currently connected SSID, if it matches the 'Home' one then use the local WiFi URL rather than the public one WifiManager wm = (WifiManager) mActContext.getSystemService(Context.WIFI_SERVICE); WifiInfo wInfo = wm.getConnectionInfo(); // somewhere read this was a quoted string but appears not to be if (wInfo.getSSID().equalsIgnoreCase(ssid)) { // the ssid will be quoted in the info class apexBaseURL = lanUri; } else { apexBaseURL = wanUri; } } else { apexBaseURL = wanUri; } // for this function we need to append to the URL. I should really // check if the "/" was put on the end by the user here to avoid // possible errors. if (!apexBaseURL.endsWith("/")) { String tmp = apexBaseURL + "/"; apexBaseURL = tmp; } // oh, we should also check if it starts with an "http://" if (!apexBaseURL.toLowerCase().startsWith("http://")) { String tmp = "http://" + apexBaseURL; apexBaseURL = tmp; } // we should also check if it ends with an "status.sht" on the end and remove it. // This used to be common for both the Apex and ACiii but during // the 4.04 beta Apex release it seemed to have broke and forced // me to use status.sht for the Apex. Maybe it was fixed but I // haven't checked it. // edit - this was not needed for the longest while but now that we are pushing just one // outlet, the different methods seem to be needed again. Really not sure why. String apexURL; if (model.equalsIgnoreCase("AC4")) { apexURL = apexBaseURL + "status.sht"; } else { apexURL = apexBaseURL + "cgi-bin/status.cgi"; } //Create credentials for basic auth // create a basic credentials provider and pass the credentials // Set credentials provider for our default http client so it will use those credentials UsernamePasswordCredentials c = new UsernamePasswordCredentials(user, pw); BasicCredentialsProvider cP = new BasicCredentialsProvider(); cP.setCredentials(AuthScope.ANY, c); ((DefaultHttpClient) mHttpClient).setCredentialsProvider(cP); // Build the POST update which looks like this: // form="status" // method="post" // action="status.sht" // // name="T5s_state", value="0" (0=Auto, 1=Man Off, 2=Man On) // submit -> name="Update", value="Update" // -- or // name="FeedSel", value="0" (0=A, 1=B) // submit -> name="FeedCycle", value="Feed" // -- or // submit -> name="FeedCycle", value="Feed Cancel" HttpPost httppost = new HttpPost(apexURL); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); // Add your data nameValuePairs.add(new BasicNameValuePair("name", "status")); nameValuePairs.add(new BasicNameValuePair("method", "post")); if (model.equalsIgnoreCase("AC4")) { nameValuePairs.add(new BasicNameValuePair("action", "status.sht")); } else { nameValuePairs.add(new BasicNameValuePair("action", "/cgi-bin/status.cgi")); } String cycleNumberString = Integer.toString(cycleNumber).trim(); if (cycleNumber < 4) { nameValuePairs.add(new BasicNameValuePair("FeedSel", cycleNumberString)); nameValuePairs.add(new BasicNameValuePair("FeedCycle", "Feed")); } else { nameValuePairs.add(new BasicNameValuePair("FeedCycle", "Feed Cancel")); } nameValuePairs.add(new BasicNameValuePair("Update", "Update")); try { httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse resp = mHttpClient.execute(httppost); final int status = resp.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { throw new HandlerException( "Unexpected server response " + resp.getStatusLine() + " for " + httppost.getRequestLine()); } } catch (HandlerException e) { throw e; } catch (ClientProtocolException e) { throw new HandlerException("Problem reading remote response for " + httppost.getRequestLine(), e); } catch (IOException e) { throw new HandlerException("Problem reading remote response for " + httppost.getRequestLine(), e); } }
From source file:org.fao.geonet.utils.AbstractHttpRequest.java
protected ClientHttpResponse doExecute(final HttpRequestBase httpMethod) throws IOException { return requestFactory.execute(httpMethod, new Function<HttpClientBuilder, Void>() { @Nullable//from w w w. j ava2 s. c o m @Override public Void apply(@Nonnull HttpClientBuilder input) { final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); if (credentials != null) { final URI uri = httpMethod.getURI(); HttpHost hh = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); credentialsProvider.setCredentials(new AuthScope(hh), credentials); // Preemptive authentication if (isPreemptiveBasicAuth()) { // 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(hh, basicAuth); // Add AuthCache to the execution context httpClientContext = HttpClientContext.create(); httpClientContext.setCredentialsProvider(credentialsProvider); httpClientContext.setAuthCache(authCache); } else { input.setDefaultCredentialsProvider(credentialsProvider); } } else { input.setDefaultCredentialsProvider(credentialsProvider); } if (useProxy) { final HttpHost proxy = new HttpHost(proxyHost, proxyPort); input.setProxy(proxy); if (proxyCredentials != null) { credentialsProvider.setCredentials(new AuthScope(proxy), proxyCredentials); } } input.setRedirectStrategy(new LaxRedirectStrategy()); return null; } }, this); }
From source file:org.sonatype.nexus.ant.staging.deploy.ZapperImpl.java
@Override public void deployDirectory(final ZapperRequest zapperRequest) throws IOException { try {//from w w w. j av a 2 s . co m HttpHost proxyServer = null; BasicCredentialsProvider credentialsProvider = null; if (!StringUtils.isBlank(zapperRequest.getProxyProtocol())) { proxyServer = new HttpHost(zapperRequest.getProxyHost(), zapperRequest.getProxyPort(), zapperRequest.getProxyProtocol()); if (!StringUtils.isBlank(zapperRequest.getProxyUsername())) { UsernamePasswordCredentials proxyCredentials = new UsernamePasswordCredentials( zapperRequest.getProxyUsername(), zapperRequest.getProxyPassword()); credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(proxyServer.getHostName(), proxyServer.getPort(), AuthScope.ANY_REALM, proxyServer.getSchemeName()), proxyCredentials); } } if (!StringUtils.isBlank(zapperRequest.getRemoteUsername())) { UsernamePasswordCredentials remoteCredentials = new UsernamePasswordCredentials( zapperRequest.getRemoteUsername(), zapperRequest.getRemotePassword()); if (credentialsProvider == null) { credentialsProvider = new BasicCredentialsProvider(); } credentialsProvider.setCredentials(AuthScope.ANY, remoteCredentials); } final Parameters parameters = ParametersBuilder.defaults().build(); final Hc4ClientBuilder clientBuilder = new Hc4ClientBuilder(parameters, zapperRequest.getRemoteUrl()); if (credentialsProvider != null) { clientBuilder.withPreemptiveRealm(credentialsProvider); } if (proxyServer != null) { clientBuilder.withProxy(proxyServer); } final Client client = clientBuilder.build(); final IOSourceListable deployables = new DirectoryIOSource(zapperRequest.getStageRepository()); try { client.upload(deployables); } finally { client.close(); } } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException("Unable to deploy!", e); } }