From eea9427f52f6efca07a1acefd92917eb3bc7ab64 Mon Sep 17 00:00:00 2001 From: Kedar Date: Mon, 18 Mar 2019 16:47:52 +0530 Subject: [PATCH 1/2] 1. Added http socket factory in registry as CONNECT method needs it 2. Added NTCredentials if username contains / or \. Perhaps adding domain in proxyconfig might be better --- .../intuit/oauth2/http/HttpRequestClient.java | 421 +++++++++--------- 1 file changed, 201 insertions(+), 220 deletions(-) diff --git a/oauth2-platform-api/src/main/java/com/intuit/oauth2/http/HttpRequestClient.java b/oauth2-platform-api/src/main/java/com/intuit/oauth2/http/HttpRequestClient.java index 011e52c7..2bc72710 100644 --- a/oauth2-platform-api/src/main/java/com/intuit/oauth2/http/HttpRequestClient.java +++ b/oauth2-platform-api/src/main/java/com/intuit/oauth2/http/HttpRequestClient.java @@ -15,21 +15,19 @@ *******************************************************************************/ package com.intuit.oauth2.http; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.security.KeyStore; -import java.util.ArrayList; -import java.util.List; - -import javax.net.ssl.SSLContext; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpHost; -import org.apache.http.HttpResponse; -import org.apache.http.HttpVersion; -import org.apache.http.NameValuePair; +import com.intuit.oauth2.config.ProxyConfig; +import com.intuit.oauth2.data.OAuthMigrationRequest; +import com.intuit.oauth2.exception.InvalidRequestException; +import com.intuit.oauth2.utils.LoggerImpl; +import com.intuit.oauth2.utils.PropertiesConfig; +import oauth.signpost.OAuthConsumer; +import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; +import oauth.signpost.exception.OAuthCommunicationException; +import oauth.signpost.exception.OAuthExpectationFailedException; +import oauth.signpost.exception.OAuthMessageSignerException; +import org.apache.http.*; import org.apache.http.auth.AuthScope; +import org.apache.http.auth.NTCredentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CredentialsProvider; @@ -40,6 +38,7 @@ import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLContexts; @@ -53,233 +52,215 @@ import org.apache.http.message.BasicHeader; import org.slf4j.Logger; -import com.intuit.oauth2.config.ProxyConfig; -import com.intuit.oauth2.data.OAuthMigrationRequest; -import com.intuit.oauth2.exception.InvalidRequestException; -import com.intuit.oauth2.utils.LoggerImpl; -import com.intuit.oauth2.utils.PropertiesConfig; - -import oauth.signpost.OAuthConsumer; -import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; -import oauth.signpost.exception.OAuthCommunicationException; -import oauth.signpost.exception.OAuthExpectationFailedException; -import oauth.signpost.exception.OAuthMessageSignerException; +import javax.net.ssl.SSLContext; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.KeyStore; +import java.util.ArrayList; +import java.util.List; /** * Client class to make http request calls - * - * @author dderose * + * @author dderose */ public class HttpRequestClient { - - private final CloseableHttpClient client; - - private static final int CONNECTION_TIMEOUT = 10000; - private static final int SOCKET_TIMEOUT = 30000; - - private static final Logger logger = LoggerImpl.getInstance(); - - /** - * Build the HttpClient - * - */ - public HttpRequestClient(ProxyConfig proxyConfig) { - RequestConfig config = RequestConfig.custom() - .setConnectTimeout(CONNECTION_TIMEOUT) - .setSocketTimeout(SOCKET_TIMEOUT).build(); - - //add default headers - List headers = new ArrayList(); - headers.add(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "utf-8")); - headers.add(new BasicHeader(HttpHeaders.ACCEPT, "application/json")); - headers.add(new BasicHeader(HttpHeaders.USER_AGENT, "V3JavaSDK-OAuth2-" + PropertiesConfig.getInstance().getProperty("version"))); - - //build the client - Registry socketFactoryRegistry = RegistryBuilder. create().register("https", prepareClientSSL()).build(); - PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager( - socketFactoryRegistry); - HttpClientBuilder hcBuilder = HttpClients.custom() - .setConnectionManager(cm) - .setDefaultRequestConfig(config) - .setDefaultHeaders(headers) - .setMaxConnPerRoute(10) - .setDefaultCredentialsProvider(setProxyAuthentication(proxyConfig)); - - // getting proxy from Config file. - HttpHost proxy = getProxy(proxyConfig); - - if (proxy != null) { - hcBuilder.setProxy(proxy); - } - client = hcBuilder.build(); - } - - /** - * Method to make the HTTP request call using the request attributes supplied - * - * @param request - * @return - * @throws InvalidRequestException - */ - public Response makeRequest(Request request) throws InvalidRequestException { - - logger.debug("Enter HttpRequestClient::makeRequest"); - - //prepare request - RequestBuilder builder = RequestBuilder.create(request.getMethod().value()) - .setUri(request.constructURL().toString()) - .setVersion(HttpVersion.HTTP_1_1) - .setCharset(StandardCharsets.UTF_8); - - //add auth header - if (request.isRequiresAuthentication()) { - builder.addHeader(HttpHeaders.AUTHORIZATION, request.getAuthString()); - } - - MethodType method = request.getMethod(); - if (method == MethodType.POST) { - //add post header - builder.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); - - //add post params - for (NameValuePair nvp : request.getPostParams()) { - builder.addParameter(nvp); - } - } - - logger.debug("Request URI : " + builder.getUri()); - logger.debug("Http Method : " + builder.getMethod()); - - try { - //make the call - HttpResponse response = client.execute(builder.build()); - //prepare response - return new Response( - response.getEntity() == null ? null : response.getEntity().getContent(), - response.getStatusLine().getStatusCode() - ); - } catch (IOException e) { - logger.error("Exception while making httpRequest", e); - throw new InvalidRequestException(e.getMessage()); - } - - } - - /** - * Method to make the HTTP POST request using the request attributes supplied - * - * @param request - * @return - * @throws InvalidRequestException - */ - public Response makeJsonRequest(Request request, OAuthMigrationRequest migrationRequest) throws InvalidRequestException { - - logger.debug("Enter HttpRequestClient::makeJsonRequest"); - //create oauth consumer using tokens - OAuthConsumer consumer = new CommonsHttpOAuthConsumer(migrationRequest.getConsumerKey(), migrationRequest.getConsumerSecret()); + + private static final int CONNECTION_TIMEOUT = 10000; + private static final int SOCKET_TIMEOUT = 30000; + private static final Logger logger = LoggerImpl.getInstance(); + private final CloseableHttpClient client; + + /** + * Build the HttpClient + */ + public HttpRequestClient(ProxyConfig proxyConfig) { + RequestConfig config = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build(); + + //add default headers + List headers = new ArrayList(); + headers.add(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "utf-8")); + headers.add(new BasicHeader(HttpHeaders.ACCEPT, "application/json")); + headers.add(new BasicHeader(HttpHeaders.USER_AGENT, "V3JavaSDK-OAuth2-" + PropertiesConfig.getInstance().getProperty("version"))); + + //build the client + Registry socketFactoryRegistry = RegistryBuilder.create().register("https", prepareClientSSL()).register("http", new PlainConnectionSocketFactory()).build(); + PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry); + HttpClientBuilder hcBuilder = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(config).setDefaultHeaders(headers).setMaxConnPerRoute(10).setDefaultCredentialsProvider(setProxyAuthentication(proxyConfig)); + + // getting proxy from Config file. + HttpHost proxy = getProxy(proxyConfig); + + if (proxy != null) { + hcBuilder.setProxy(proxy); + } + client = hcBuilder.build(); + } + + public SSLConnectionSocketFactory prepareClientSSL() { + try { + KeyStore trustStore = null; + SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); + + String tlsVersion = PropertiesConfig.getInstance().getProperty("TLS_VERSION"); + SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(sslContext, new String[]{tlsVersion}, null, new NoopHostnameVerifier()); + return sslConnectionFactory; + } catch (Exception ex) { + logger.error("couldn't create httpClient!! {}", ex.getMessage(), ex); + return null; + } + } + + /** + * Method to set proxy authentication + * + * @return + */ + public CredentialsProvider setProxyAuthentication(ProxyConfig proxyConfig) { + + if (proxyConfig == null) { + return null; + } + String username = proxyConfig.getUsername(); + String password = proxyConfig.getPassword(); + + if (!username.isEmpty() && !password.isEmpty()) { + String host = proxyConfig.getHost(); + String port = proxyConfig.getPort(); + if (!host.isEmpty() && !port.isEmpty()) { + CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + if (username.contains("/") || username.contains("\\")) { + int index = username.indexOf("/") > 0 ? username.indexOf("/") : username.indexOf("\\"); + String domain = username.substring(0, index); + String user = username.substring(index + 1, username.length()); + credentialsProvider.setCredentials(new AuthScope(host, Integer.parseInt(port)), new NTCredentials(user, password, host, domain)); + } else { + credentialsProvider.setCredentials(new AuthScope(host, Integer.parseInt(port)), new UsernamePasswordCredentials(username, password)); + } + return credentialsProvider; + } + } + return null; + } + + /** + * Method to get proxy + * + * @return returns HttpHost + */ + public HttpHost getProxy(ProxyConfig proxyConfig) { + if (proxyConfig == null) { + return null; + } + String host = proxyConfig.getHost(); + String port = proxyConfig.getPort(); + HttpHost proxy = null; + if (!host.isEmpty() && !port.isEmpty()) { + proxy = new HttpHost(host, Integer.parseInt(port)); + + } + return proxy; + } + + /** + * Method to make the HTTP request call using the request attributes supplied + * + * @param request + * @return + * @throws InvalidRequestException + */ + public Response makeRequest(Request request) throws InvalidRequestException { + + logger.debug("Enter HttpRequestClient::makeRequest"); + + //prepare request + RequestBuilder builder = RequestBuilder.create(request.getMethod().value()).setUri(request.constructURL().toString()).setVersion(HttpVersion.HTTP_1_1).setCharset(StandardCharsets.UTF_8); + + //add auth header + if (request.isRequiresAuthentication()) { + builder.addHeader(HttpHeaders.AUTHORIZATION, request.getAuthString()); + } + + MethodType method = request.getMethod(); + if (method == MethodType.POST) { + //add post header + builder.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); + + //add post params + for (NameValuePair nvp : request.getPostParams()) { + builder.addParameter(nvp); + } + } + + logger.debug("Request URI : " + builder.getUri()); + logger.debug("Http Method : " + builder.getMethod()); + + try { + //make the call + HttpResponse response = client.execute(builder.build()); + //prepare response + return new Response(response.getEntity() == null ? null : response.getEntity().getContent(), response.getStatusLine().getStatusCode()); + } catch (IOException e) { + logger.error("Exception while making httpRequest", e); + throw new InvalidRequestException(e.getMessage()); + } + + } + + /** + * Method to make the HTTP POST request using the request attributes supplied + * + * @param request + * @return + * @throws InvalidRequestException + */ + public Response makeJsonRequest(Request request, OAuthMigrationRequest migrationRequest) throws InvalidRequestException { + + logger.debug("Enter HttpRequestClient::makeJsonRequest"); + //create oauth consumer using tokens + OAuthConsumer consumer = new CommonsHttpOAuthConsumer(migrationRequest.getConsumerKey(), migrationRequest.getConsumerSecret()); consumer.setTokenWithSecret(migrationRequest.getAccessToken(), migrationRequest.getAccessSecret()); - HttpPost post = new HttpPost(request.constructURL().toString()); - + HttpPost post = new HttpPost(request.constructURL().toString()); + //sign - try { + try { consumer.sign(post); } catch (OAuthMessageSignerException e) { logger.error("Exception while making httpRequest", e); - throw new InvalidRequestException(e.getMessage()); + throw new InvalidRequestException(e.getMessage()); } catch (OAuthExpectationFailedException e) { logger.error("Exception while making httpRequest", e); - throw new InvalidRequestException(e.getMessage()); + throw new InvalidRequestException(e.getMessage()); } catch (OAuthCommunicationException e) { logger.error("Exception while making httpRequest", e); - throw new InvalidRequestException(e.getMessage()); + throw new InvalidRequestException(e.getMessage()); } - - //add headers - post.setHeader("Accept", "application/json"); - post.setHeader("Content-Type", "application/json"); - - // add post data - HttpEntity entity = new StringEntity(request.getPostJson(), "UTF-8"); - post.setEntity(entity); - - CloseableHttpResponse httpResponse = null; - try { - //make the call + + //add headers + post.setHeader("Accept", "application/json"); + post.setHeader("Content-Type", "application/json"); + + // add post data + HttpEntity entity = new StringEntity(request.getPostJson(), "UTF-8"); + post.setEntity(entity); + + CloseableHttpResponse httpResponse = null; + try { + //make the call httpResponse = client.execute(post); - //prepare response - return new Response( - httpResponse.getEntity() == null ? null : httpResponse.getEntity().getContent(), - httpResponse.getStatusLine().getStatusCode() - ); - - + //prepare response + return new Response(httpResponse.getEntity() == null ? null : httpResponse.getEntity().getContent(), httpResponse.getStatusLine().getStatusCode()); + + } catch (ClientProtocolException e) { logger.error("Exception while making httpRequest", e); - throw new InvalidRequestException(e.getMessage()); + throw new InvalidRequestException(e.getMessage()); } catch (IOException e) { logger.error("Exception while making httpRequest", e); - throw new InvalidRequestException(e.getMessage()); - } - - } - - /** - * Method to set proxy authentication - * - * @return - */ - public CredentialsProvider setProxyAuthentication(ProxyConfig proxyConfig) { - - if(proxyConfig == null) { - return null; - } - String username = proxyConfig.getUsername(); - String password = proxyConfig.getPassword(); - - if (!username.isEmpty() && !password.isEmpty()) { - String host = proxyConfig.getHost(); - String port = proxyConfig.getPort(); - if (!host.isEmpty() && !port.isEmpty()) { - CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); - credentialsProvider.setCredentials(new AuthScope(host, Integer.parseInt(port)), new UsernamePasswordCredentials(username, password)); - return credentialsProvider; - } - } - return null; - } - - public SSLConnectionSocketFactory prepareClientSSL() { - try { - KeyStore trustStore = null; - SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); - - String tlsVersion = PropertiesConfig.getInstance().getProperty("TLS_VERSION"); - SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(sslContext, new String[]{tlsVersion}, null, new NoopHostnameVerifier()); - return sslConnectionFactory; - } catch (Exception ex) { - logger.error("couldn't create httpClient!! {}", ex.getMessage(), ex); - return null; - } - } - - /** - * Method to get proxy - * - * @return returns HttpHost - */ - public HttpHost getProxy(ProxyConfig proxyConfig) { - if(proxyConfig == null) { - return null; - } - String host = proxyConfig.getHost(); - String port = proxyConfig.getPort(); - HttpHost proxy = null; - if (!host.isEmpty() && !port.isEmpty()) { - proxy = new HttpHost(host, Integer.parseInt(port)); - } - return proxy; - } + throw new InvalidRequestException(e.getMessage()); + } + + } } From 202ef8e6215c807be0337a8ea685fe8d2f812fcf Mon Sep 17 00:00:00 2001 From: Kedar Date: Thu, 28 Mar 2019 22:29:00 +0530 Subject: [PATCH 2/2] 1. Added domain in ProxyConfig 2. Added NTCredentials if domain not empty in HttpRequestClinent --- .../com/intuit/oauth2/config/ProxyConfig.java | 38 ++++++++++++------- .../intuit/oauth2/http/HttpRequestClient.java | 8 ++-- 2 files changed, 27 insertions(+), 19 deletions(-) diff --git a/oauth2-platform-api/src/main/java/com/intuit/oauth2/config/ProxyConfig.java b/oauth2-platform-api/src/main/java/com/intuit/oauth2/config/ProxyConfig.java index 4ba3e70c..e4b6f293 100644 --- a/oauth2-platform-api/src/main/java/com/intuit/oauth2/config/ProxyConfig.java +++ b/oauth2-platform-api/src/main/java/com/intuit/oauth2/config/ProxyConfig.java @@ -17,9 +17,8 @@ /** * Config class to hold the proxy properties - * - * @author dderose * + * @author dderose */ public class ProxyConfig { @@ -27,15 +26,16 @@ public class ProxyConfig { private String port; private String username; private String password; - + private String domain; + private ProxyConfig(ProxyConfigBuilder builder) { - this.host = builder.host; - this.port = builder.port; - this.username = builder.username; - this.password = builder.password; - + this.host = builder.host; + this.port = builder.port; + this.username = builder.username; + this.password = builder.password; + this.domain = builder.domain; } - + public String getHost() { return host; } @@ -52,33 +52,43 @@ public String getPassword() { return password; } + public String getDomain() { + return domain; + } + public static class ProxyConfigBuilder { - + private String host; private String port; private String username; private String password; + private String domain; public ProxyConfigBuilder(String host, String port) { this.host = host; this.port = port; } - + public ProxyConfigBuilder username(String username) { this.username = username; return this; } - + public ProxyConfigBuilder password(String password) { this.password = password; return this; } + public ProxyConfigBuilder domain(String domain) { + this.domain = domain; + return this; + } + public ProxyConfig buildConfig() { return new ProxyConfig(this); } - + } - + } diff --git a/oauth2-platform-api/src/main/java/com/intuit/oauth2/http/HttpRequestClient.java b/oauth2-platform-api/src/main/java/com/intuit/oauth2/http/HttpRequestClient.java index 2bc72710..4c3551de 100644 --- a/oauth2-platform-api/src/main/java/com/intuit/oauth2/http/HttpRequestClient.java +++ b/oauth2-platform-api/src/main/java/com/intuit/oauth2/http/HttpRequestClient.java @@ -129,11 +129,9 @@ public CredentialsProvider setProxyAuthentication(ProxyConfig proxyConfig) { String port = proxyConfig.getPort(); if (!host.isEmpty() && !port.isEmpty()) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); - if (username.contains("/") || username.contains("\\")) { - int index = username.indexOf("/") > 0 ? username.indexOf("/") : username.indexOf("\\"); - String domain = username.substring(0, index); - String user = username.substring(index + 1, username.length()); - credentialsProvider.setCredentials(new AuthScope(host, Integer.parseInt(port)), new NTCredentials(user, password, host, domain)); + String domain=proxyConfig.getDomain(); + if (!domain.isEmpty()) { + credentialsProvider.setCredentials(new AuthScope(host, Integer.parseInt(port)), new NTCredentials(username, password, host, domain)); } else { credentialsProvider.setCredentials(new AuthScope(host, Integer.parseInt(port)), new UsernamePasswordCredentials(username, password)); }