List of usage examples for org.apache.http.impl.client BasicCredentialsProvider BasicCredentialsProvider
public BasicCredentialsProvider()
From source file:com.garethahealy.resteastpathparamescape.utils.RestFactory.java
protected HttpClientContext getBasicAuthContext(URI uri, String userName, String password) { HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(userName, password)); // Create AuthCache instance // Generate BASIC scheme object and add it to the local auth cache AuthCache authCache = new BasicAuthCache(); authCache.put(targetHost, new BasicScheme()); // Add AuthCache to the execution context HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache);//from w w w .jav a 2 s. c om return context; }
From source file:com.cloudbees.plugins.binarydeployer.http.HttpRepository.java
@Override protected void deploy(List<Binary> binaries, Run run) throws IOException { CloseableHttpClient client = null;/*from w w w . java 2 s.c om*/ try { if (credentialsId == null || credentialsId.isEmpty()) { client = HttpClients.createDefault(); } else { BasicCredentialsProvider credentials = new BasicCredentialsProvider(); StandardUsernamePasswordCredentials credentialById = CredentialsProvider.findCredentialById( credentialsId, StandardUsernamePasswordCredentials.class, run, Lists.<DomainRequirement>newArrayList()); credentials.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( credentialById.getUsername(), credentialById.getPassword().getPlainText())); client = HttpClients.custom().setDefaultCredentialsProvider(credentials).disableAutomaticRetries() .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)).build(); } for (Binary binary : binaries) { BufferedHttpEntity entity = new BufferedHttpEntity( new InputStreamEntity(binary.getFile().open(), binary.getFile().length())); HttpPost post = new HttpPost(remoteLocation + binary.getName()); post.setEntity(entity); CloseableHttpResponse response = null; try { response = client.execute(post); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { log.fine("Deployed " + binary.getName() + " to " + remoteLocation); } else { log.warning("Cannot deploy file " + binary.getName() + ". Response from target was " + statusCode); run.setResult(Result.FAILURE); throw new IOException(response.getStatusLine().toString()); } } finally { if (response != null) { response.close(); } } } } finally { if (client != null) { client.close(); } } }
From source file:com.liferay.jsonwebserviceclient.JSONWebServiceClientImpl.java
public void afterPropertiesSet() { HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder.setConnectionManager(getPoolingHttpClientConnectionManager()); if ((_login != null) && (_password != null)) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(_hostName, _hostPort), new UsernamePasswordCredentials(_login, _password)); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); httpClientBuilder.setRetryHandler(new HttpRequestRetryHandlerImpl()); } else {/* w w w .j a v a2s. co m*/ if (_logger.isWarnEnabled()) { _logger.warn("Login and password are required"); } } try { setProxyHost(httpClientBuilder); _closeableHttpClient = httpClientBuilder.build(); if (_logger.isDebugEnabled()) { _logger.debug("Configured client for " + _protocol + "://" + _hostName); } } catch (Exception e) { _logger.error("Unable to configure client", e); } }
From source file:org.kaaproject.kaa.server.appenders.rest.appender.RestLogAppender.java
@Override protected void initFromConfiguration(LogAppenderDto appender, RestConfig configuration) { this.configuration = configuration; this.executor = Executors.newFixedThreadPool(configuration.getConnectionPoolSize()); target = new HttpHost(configuration.getHost(), configuration.getPort(), configuration.getSsl() ? "https" : "http"); HttpClientBuilder builder = HttpClients.custom(); if (configuration.getUsername() != null && configuration.getPassword() != null) { LOG.info("Adding basic auth credentials provider"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword())); builder.setDefaultCredentialsProvider(credsProvider); }/*from ww w .j a va 2 s .c o m*/ if (!configuration.getVerifySslCert()) { LOG.info("Adding trustful ssl context"); SSLContextBuilder sslBuilder = new SSLContextBuilder(); try { sslBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslBuilder.build()); builder.setSSLSocketFactory(sslsf); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) { LOG.error("Failed to init socket factory {}", ex.getMessage(), ex); } } PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setDefaultMaxPerRoute(configuration.getConnectionPoolSize()); cm.setMaxTotal(configuration.getConnectionPoolSize()); builder.setConnectionManager(cm); this.client = builder.build(); }
From source file:org.activiti.webservice.WebServiceSendActivitiBehavior.java
public void execute(ActivityExecution execution) throws Exception { String endpointUrlValue = this.getStringFromField(this.endpointUrl, execution); String languageValue = this.getStringFromField(this.language, execution); String payloadExpressionValue = this.getStringFromField(this.payloadExpression, execution); String resultVariableValue = this.getStringFromField(this.resultVariable, execution); String usernameValue = this.getStringFromField(this.username, execution); String passwordValue = this.getStringFromField(this.password, execution); ScriptingEngines scriptingEngines = Context.getProcessEngineConfiguration().getScriptingEngines(); Object payload = scriptingEngines.evaluate(payloadExpressionValue, languageValue, execution); if (endpointUrlValue.startsWith("vm:")) { LocalWebServiceClient client = this.getWebServiceContext().getClient(); WebServiceMessage message = new DefaultWebServiceMessage(payload, this.getWebServiceContext()); WebServiceMessage resultMessage = client.send(endpointUrlValue, message); Object result = resultMessage.getPayload(); if (resultVariableValue != null) { execution.setVariable(resultVariableValue, result); }// w w w. j a va2 s.c o m } else { HttpClientBuilder clientBuilder = HttpClientBuilder.create(); if (usernameValue != null && passwordValue != null) { CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(usernameValue, passwordValue); provider.setCredentials(new AuthScope("localhost", -1, "webservice-realm"), credentials); clientBuilder.setDefaultCredentialsProvider(provider); } HttpClient client = clientBuilder.build(); HttpPost request = new HttpPost(endpointUrlValue); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(payload); oos.flush(); oos.close(); request.setEntity(new ByteArrayEntity(baos.toByteArray())); } catch (Exception e) { throw new ActivitiException("Error setting message payload", e); } byte[] responseBytes = null; try { // execute the POST request HttpResponse response = client.execute(request); responseBytes = IOUtils.toByteArray(response.getEntity().getContent()); } finally { // release any connection resources used by the method request.releaseConnection(); } if (responseBytes != null) { try { ByteArrayInputStream in = new ByteArrayInputStream(responseBytes); ObjectInputStream is = new ObjectInputStream(in); Object result = is.readObject(); if (resultVariableValue != null) { execution.setVariable(resultVariableValue, result); } } catch (Exception e) { throw new ActivitiException("Failed to read response value", e); } } } this.leave(execution); }
From source file:org.opensaml.security.httpclient.HttpClientSecurityParameters.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. * //from w w w . j av a 2 s.c om * <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) { 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); credentialsProvider = provider; } else { credentialsProvider = null; } }
From source file:org.jboss.as.test.clustering.cluster.web.authentication.BasicAuthenticationWebFailoverTestCase.java
@Test public void test(@ArquillianResource(SecureServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1, @ArquillianResource(SecureServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2) throws IOException, URISyntaxException { CredentialsProvider provider = new BasicCredentialsProvider(); HttpClient client = HttpClients.custom().setDefaultCredentialsProvider(provider).build(); URI uri1 = SecureServlet.createURI(baseURL1); URI uri2 = SecureServlet.createURI(baseURL2); try {//w ww .j a v a 2 s . co m // Valid login, invalid role setCredentials(provider, "forbidden", "password", baseURL1, baseURL2); HttpResponse response = client.execute(new HttpGet(uri1)); try { Assert.assertEquals(HttpServletResponse.SC_FORBIDDEN, response.getStatusLine().getStatusCode()); } finally { HttpClientUtils.closeQuietly(response); } // Invalid login, valid role setCredentials(provider, "allowed", "bad", baseURL1, baseURL2); response = client.execute(new HttpGet(uri1)); try { Assert.assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); } finally { HttpClientUtils.closeQuietly(response); } // Valid login, valid role setCredentials(provider, "allowed", "password", baseURL1, baseURL2); String sessionId = null; response = client.execute(new HttpGet(uri1)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertNotNull(response.getFirstHeader(SecureServlet.SESSION_ID_HEADER)); sessionId = response.getFirstHeader(SecureServlet.SESSION_ID_HEADER).getValue(); } finally { HttpClientUtils.closeQuietly(response); } undeploy(DEPLOYMENT_1); response = client.execute(new HttpGet(uri2)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(sessionId, response.getFirstHeader(SecureServlet.SESSION_ID_HEADER).getValue()); } finally { HttpClientUtils.closeQuietly(response); } deploy(DEPLOYMENT_1); response = client.execute(new HttpGet(uri1)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(sessionId, response.getFirstHeader(SecureServlet.SESSION_ID_HEADER).getValue()); } finally { HttpClientUtils.closeQuietly(response); } } finally { HttpClientUtils.closeQuietly(client); } }
From source file:ch.sbb.releasetrain.utils.http.HttpUtilImpl.java
/** * authenticates the context if user and password are set *//* www.j a v a 2s .c o m*/ private HttpClientContext initAuthIfNeeded(String url) { HttpClientContext context = HttpClientContext.create(); if (this.user.isEmpty() || this.password.isEmpty()) { log.debug( "http connection without autentication, because no user / password ist known to HttpUtilImpl ..."); return context; } CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(user, password)); URL url4Host; try { url4Host = new URL(url); } catch (MalformedURLException e) { log.error(e.getMessage(), e); return context; } HttpHost targetHost = new HttpHost(url4Host.getHost(), url4Host.getPort(), url4Host.getProtocol()); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); return context; }
From source file:org.openrepose.commons.utils.http.ServiceClient.java
private HttpClient getClientWithBasicAuth() throws ServiceClientException { HttpClientResponse clientResponse = null; try {//from w w w.j ava2 s. c o m clientResponse = httpClientService.getClient(connectionPoolId); final HttpClient client = clientResponse.getHttpClient(); if (!StringUtilities.isEmpty(targetHostUri) && !StringUtilities.isEmpty(username) && !StringUtilities.isEmpty(password)) { client.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, AuthPolicy.BASIC); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHostUri, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password)); client.getParams().setParameter("http.authentication.credential-provider", credsProvider); } return client; } catch (HttpClientNotFoundException e) { LOG.error("Failed to obtain an HTTP default client connection"); throw new ServiceClientException("Failed to obtain an HTTP default client connection", e); } finally { if (clientResponse != null) { httpClientService.releaseClient(clientResponse); } } }
From source file:org.apache.jena.fuseki.embedded.TestFusekiTestAuth.java
@Test(expected = HttpException.class) public void testServer_auth_bad_password() { BasicCredentialsProvider credsProv = new BasicCredentialsProvider(); credsProv.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USER, "WRONG")); HttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProv).build(); try (TypedInputStream in = HttpOp.execHttpGet(FusekiTestAuth.urlDataset(), "*/*", client, null)) { } catch (HttpException ex) { throw assertAuthHttpException(ex); }/*from ww w . j av a2 s .c om*/ }