use of org.apache.http.client.CredentialsProvider in project weixin-java-tools by chanjarster.
the class WxMpServiceImpl method setWxMpConfigStorage.
public void setWxMpConfigStorage(WxMpConfigStorage wxConfigProvider) {
this.wxMpConfigStorage = wxConfigProvider;
String http_proxy_host = wxMpConfigStorage.getHttp_proxy_host();
int http_proxy_port = wxMpConfigStorage.getHttp_proxy_port();
String http_proxy_username = wxMpConfigStorage.getHttp_proxy_username();
String http_proxy_password = wxMpConfigStorage.getHttp_proxy_password();
final HttpClientBuilder builder = HttpClients.custom();
if (StringUtils.isNotBlank(http_proxy_host)) {
// 使用代理服务器
if (StringUtils.isNotBlank(http_proxy_username)) {
// 需要用户认证的代理服务器
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(http_proxy_host, http_proxy_port), new UsernamePasswordCredentials(http_proxy_username, http_proxy_password));
builder.setDefaultCredentialsProvider(credsProvider);
} else {
// 无需用户认证的代理服务器
}
httpProxy = new HttpHost(http_proxy_host, http_proxy_port);
}
if (wxConfigProvider.getSSLContext() != null) {
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(wxConfigProvider.getSSLContext(), new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
builder.setSSLSocketFactory(sslsf);
}
httpClient = builder.build();
}
use of org.apache.http.client.CredentialsProvider in project syncany by syncany.
the class CommandLineClient method sendToRest.
private int sendToRest(Command command, String commandName, String[] commandArgs, File portFile) {
try {
// Read port config (for daemon) from port file
PortTO portConfig = readPortConfig(portFile);
// Create authentication details
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(SERVER_HOSTNAME, portConfig.getPort()), new UsernamePasswordCredentials(portConfig.getUser().getUsername(), portConfig.getUser().getPassword()));
// Allow all hostnames in CN; this is okay as long as hostname is localhost/127.0.0.1!
// See: https://github.com/syncany/syncany/pull/196#issuecomment-52197017
X509HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier();
// Fetch the SSL context (using the user key/trust store)
SSLContext sslContext = UserConfig.createUserSSLContext();
// Create client with authentication details
CloseableHttpClient client = HttpClients.custom().setSslcontext(sslContext).setHostnameVerifier(hostnameVerifier).setDefaultCredentialsProvider(credentialsProvider).build();
// Build and send request, print response
Request request = buildFolderRequestFromCommand(command, commandName, commandArgs, config.getLocalDir().getAbsolutePath());
String serverUri = SERVER_SCHEMA + SERVER_HOSTNAME + ":" + portConfig.getPort() + SERVER_REST_API;
String xmlMessageString = XmlMessageFactory.toXml(request);
StringEntity xmlMessageEntity = new StringEntity(xmlMessageString);
HttpPost httpPost = new HttpPost(serverUri);
httpPost.setEntity(xmlMessageEntity);
logger.log(Level.INFO, "Sending HTTP Request to: " + serverUri);
logger.log(Level.FINE, httpPost.toString());
logger.log(Level.FINE, xmlMessageString);
HttpResponse httpResponse = client.execute(httpPost);
int exitCode = handleRestResponse(command, httpResponse);
return exitCode;
} catch (Exception e) {
logger.log(Level.SEVERE, "Command " + command.toString() + " FAILED. ", e);
return showErrorAndExit(e.getMessage());
}
}
use of org.apache.http.client.CredentialsProvider in project openhab1-addons by openhab.
the class Tr064Comm method createTr064HttpClient.
/***
* Creates a apache HTTP Client object, ignoring SSL Exceptions like self signed certificates
* and sets Auth. Scheme to Digest Auth
*
* @param fboxUrl the URL from config file of fbox to connect to
* @return the ready-to-use httpclient for tr064 requests
*/
private CloseableHttpClient createTr064HttpClient(String fboxUrl) {
CloseableHttpClient hc = null;
// Convert URL String from config in easy explotable URI object
URIBuilder uriFbox = null;
try {
uriFbox = new URIBuilder(fboxUrl);
} catch (URISyntaxException e) {
logger.error("Invalid FritzBox URL! {}", e.getMessage());
return null;
}
// Create context of the http client
_httpClientContext = HttpClientContext.create();
CookieStore cookieStore = new BasicCookieStore();
_httpClientContext.setCookieStore(cookieStore);
// SETUP AUTH
// Auth is specific for this target
HttpHost target = new HttpHost(uriFbox.getHost(), uriFbox.getPort(), uriFbox.getScheme());
// Add digest authentication with username/pw from global config
CredentialsProvider credp = new BasicCredentialsProvider();
credp.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(_user, _pw));
// Create AuthCache instance. Manages authentication based on server response
AuthCache authCache = new BasicAuthCache();
// Generate DIGEST scheme object, initialize it and add it to the local auth cache. Digeste is standard for fbox
// auth SOAP
DigestScheme digestAuth = new DigestScheme();
// known from fbox specification
digestAuth.overrideParamter("realm", "HTTPS Access");
// never known at first request
digestAuth.overrideParamter("nonce", "");
authCache.put(target, digestAuth);
// Add AuthCache to the execution context
_httpClientContext.setAuthCache(authCache);
// SETUP SSL TRUST
SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
SSLConnectionSocketFactory sslsf = null;
try {
// accept self signed certs
sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
// dont
sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), null, null, new NoopHostnameVerifier());
// verify
// hostname
// against
// cert
// CN
} catch (Exception ex) {
logger.error(ex.getMessage());
}
// Set timeout values
RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(4000).setConnectTimeout(4000).setConnectionRequestTimeout(4000).build();
// BUILDER
// setup builder with parameters defined before
hc = // set the SSL options which trust every self signed
HttpClientBuilder.create().setSSLSocketFactory(sslsf).setDefaultCredentialsProvider(// set auth options using digest
credp).setDefaultRequestConfig(// set the request config specifying timeout
rc).build();
return hc;
}
use of org.apache.http.client.CredentialsProvider in project openhab1-addons by openhab.
the class HttpComponentsHelper method setup.
/**
* prepare for the https connection
* call this in the constructor of the class that does the connection if
* it's used multiple times
*/
private void setup() {
SchemeRegistry schemeRegistry = new SchemeRegistry();
// http scheme
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
// https scheme
schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
params = new BasicHttpParams();
params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 1);
params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(1));
params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "utf8");
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
// set the user credentials for our site "example.com"
credentialsProvider.setCredentials(new AuthScope("example.com", AuthScope.ANY_PORT), new UsernamePasswordCredentials("UserNameHere", "UserPasswordHere"));
clientConnectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);
context = new BasicHttpContext();
context.setAttribute("http.auth.credentials-provider", credentialsProvider);
}
use of org.apache.http.client.CredentialsProvider in project XobotOS by xamarin.
the class DefaultRequestDirector method createTunnelToTarget.
// establishConnection
/**
* Creates a tunnel to the target server.
* The connection must be established to the (last) proxy.
* A CONNECT request for tunnelling through the proxy will
* be created and sent, the response received and checked.
* This method does <i>not</i> update the connection with
* information about the tunnel, that is left to the caller.
*
* @param route the route to establish
* @param context the context for request execution
*
* @return <code>true</code> if the tunnelled route is secure,
* <code>false</code> otherwise.
* The implementation here always returns <code>false</code>,
* but derived classes may override.
*
* @throws HttpException in case of a problem
* @throws IOException in case of an IO problem
*/
protected boolean createTunnelToTarget(HttpRoute route, HttpContext context) throws HttpException, IOException {
HttpHost proxy = route.getProxyHost();
HttpHost target = route.getTargetHost();
HttpResponse response = null;
boolean done = false;
while (!done) {
done = true;
if (!this.managedConn.isOpen()) {
this.managedConn.open(route, context, this.params);
}
HttpRequest connect = createConnectRequest(route, context);
String agent = HttpProtocolParams.getUserAgent(params);
if (agent != null) {
connect.addHeader(HTTP.USER_AGENT, agent);
}
connect.addHeader(HTTP.TARGET_HOST, target.toHostString());
AuthScheme authScheme = this.proxyAuthState.getAuthScheme();
AuthScope authScope = this.proxyAuthState.getAuthScope();
Credentials creds = this.proxyAuthState.getCredentials();
if (creds != null) {
if (authScope != null || !authScheme.isConnectionBased()) {
try {
connect.addHeader(authScheme.authenticate(creds, connect));
} catch (AuthenticationException ex) {
if (this.log.isErrorEnabled()) {
this.log.error("Proxy authentication error: " + ex.getMessage());
}
}
}
}
response = requestExec.execute(connect, this.managedConn, context);
int status = response.getStatusLine().getStatusCode();
if (status < 200) {
throw new HttpException("Unexpected response to CONNECT request: " + response.getStatusLine());
}
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {
if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {
this.log.debug("Proxy requested authentication");
Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context);
try {
processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context);
} catch (AuthenticationException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn("Authentication error: " + ex.getMessage());
break;
}
}
updateAuthState(this.proxyAuthState, proxy, credsProvider);
if (this.proxyAuthState.getCredentials() != null) {
done = false;
// Retry request
if (this.reuseStrategy.keepAlive(response, context)) {
this.log.debug("Connection kept alive");
// Consume response content
HttpEntity entity = response.getEntity();
if (entity != null) {
entity.consumeContent();
}
} else {
this.managedConn.close();
}
}
} else {
// Reset proxy auth scope
this.proxyAuthState.setAuthScope(null);
}
}
}
int status = response.getStatusLine().getStatusCode();
if (status > 299) {
// Buffer response content
HttpEntity entity = response.getEntity();
if (entity != null) {
response.setEntity(new BufferedHttpEntity(entity));
}
this.managedConn.close();
throw new TunnelRefusedException("CONNECT refused by proxy: " + response.getStatusLine(), response);
}
this.managedConn.markReusable();
// Leave it to derived classes, consider insecure by default here.
return false;
}
Aggregations