Author: shijh Date: Tue Mar 15 06:06:33 2016 New Revision: 1735021 URL: http://svn.apache.org/viewvc?rev=1735021&view=rev Log: OFBIZ-6755 Update the passport component to use httpclient/core-4.4.1 instead of commons-httpclient-3.1
1. Remove commons-httpclient-3.1.jar from passport component. 2. Use httpclient 4.4.1 in base/lib instead. 3. Remove randomString methods, use RandomStringUtils.randomAlphanumeric instead. 4. Move getAllowAllHttpClient to UtilHttp. Removed: ofbiz/trunk/specialpurpose/passport/lib/ Modified: ofbiz/trunk/framework/base/src/org/ofbiz/base/util/UtilHttp.java ofbiz/trunk/specialpurpose/passport/build.xml ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/event/GitHubEvents.java ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/event/LinkedInEvents.java ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/user/GitHubAuthenticator.java ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/user/LinkedInAuthenticator.java ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/util/PassportUtil.java ofbiz/trunk/specialpurpose/solr/src/org/ofbiz/solr/SolrUtil.java Modified: ofbiz/trunk/framework/base/src/org/ofbiz/base/util/UtilHttp.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/base/src/org/ofbiz/base/util/UtilHttp.java?rev=1735021&r1=1735020&r2=1735021&view=diff ============================================================================== --- ofbiz/trunk/framework/base/src/org/ofbiz/base/util/UtilHttp.java (original) +++ ofbiz/trunk/framework/base/src/org/ofbiz/base/util/UtilHttp.java Tue Mar 15 06:06:33 2016 @@ -43,12 +43,19 @@ import java.util.Set; import java.util.StringTokenizer; import java.util.TimeZone; +import javax.net.ssl.SSLContext; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.lang.RandomStringUtils; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.ssl.SSLContexts; import org.apache.oro.text.regex.MalformedPatternException; import org.apache.oro.text.regex.Pattern; import org.apache.oro.text.regex.PatternMatcher; @@ -1439,4 +1446,28 @@ public class UtilHttp { response.setHeader("Content-Disposition", String.format("%s; filename=\"%s\"", dispositionType, filename)); } + public static CloseableHttpClient getAllowAllHttpClient() { + return getAllowAllHttpClient("component://base/config/ofbizssl.jks", "changeit"); + } + + public static CloseableHttpClient getAllowAllHttpClient(String jksStoreFileName, String jksStorePassword) { + try { + // Trust own CA and all self-signed certs + SSLContext sslContext = SSLContexts.custom() + .loadTrustMaterial(FileUtil.getFile(jksStoreFileName), jksStorePassword.toCharArray(), + new TrustSelfSignedStrategy()) + .build(); + // No host name verifier + SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( + sslContext, + NoopHostnameVerifier.INSTANCE); + CloseableHttpClient httpClient = HttpClients.custom() + .setSSLSocketFactory(sslsf) + .build(); + return httpClient; + } catch (Exception e) { + return HttpClients.createDefault(); + } + } + } Modified: ofbiz/trunk/specialpurpose/passport/build.xml URL: http://svn.apache.org/viewvc/ofbiz/trunk/specialpurpose/passport/build.xml?rev=1735021&r1=1735020&r2=1735021&view=diff ============================================================================== --- ofbiz/trunk/specialpurpose/passport/build.xml (original) +++ ofbiz/trunk/specialpurpose/passport/build.xml Tue Mar 15 06:06:33 2016 @@ -30,9 +30,9 @@ under the License. <property name="ofbiz.home.dir" value="../.."/> <path id="local.class.path"> - <fileset dir="${lib.dir}" includes="*.jar"/> <fileset dir="../../framework/base/lib" includes="*.jar"/> <fileset dir="../../framework/base/lib/j2eespecs" includes="*.jar"/> + <fileset dir="../../framework/base/lib/commons" includes="*.jar"/> <fileset dir="../../framework/base/build/lib" includes="*.jar"/> <fileset dir="../../framework/entity/lib" includes="*.jar"/> <fileset dir="../../framework/entity/build/lib" includes="*.jar"/> Modified: ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/event/GitHubEvents.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/event/GitHubEvents.java?rev=1735021&r1=1735020&r2=1735021&view=diff ============================================================================== --- ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/event/GitHubEvents.java (original) +++ ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/event/GitHubEvents.java Tue Mar 15 06:06:33 2016 @@ -20,6 +20,8 @@ package org.ofbiz.passport.event; import java.io.IOException; import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Map; @@ -28,13 +30,15 @@ import java.util.Random; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.httpclient.cookie.CookiePolicy; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.methods.PostMethod; -import org.apache.commons.httpclient.params.HttpMethodParams; +import org.apache.commons.lang.RandomStringUtils; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.impl.client.BasicResponseHandler; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; import org.ofbiz.passport.user.GitHubAuthenticator; import org.ofbiz.passport.util.PassportUtil; import org.ofbiz.base.conversion.ConversionException; @@ -52,6 +56,7 @@ import org.ofbiz.entity.Delegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.util.EntityUtil; +import org.ofbiz.entity.util.EntityUtilProperties; import org.ofbiz.product.store.ProductStoreWorker; import org.ofbiz.service.LocalDispatcher; @@ -164,25 +169,27 @@ public class GitHubEvents { String accessToken = null; String tokenType = null; - HttpClient jsonClient = new HttpClient(); - PostMethod postMethod = new PostMethod(TokenEndpoint + TokenServiceUri); try { - HttpMethodParams params = new HttpMethodParams(); - String queryString = "client_id=" + clientId - + "&client_secret=" + secret - + "&code=" + authorizationCode - + "&redirect_uri=" + URLEncoder.encode(returnURI, "UTF-8"); - // Debug.logInfo("GitHub get access token query string: " + queryString, module); - postMethod.setQueryString(queryString); - params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); - postMethod.setParams(params); - postMethod.setRequestHeader(PassportUtil.ACCEPT_HEADER, "application/json"); - jsonClient.executeMethod(postMethod); - // Debug.logInfo("GitHub get access token response code: " + postMethod.getStatusCode(), module); - // Debug.logInfo("GitHub get access token response content: " + postMethod.getResponseBodyAsString(1024), module); - if (postMethod.getStatusCode() == HttpStatus.SC_OK) { - // Debug.logInfo("Json Response from GitHub: " + postMethod.getResponseBodyAsString(1024), module); - JSON jsonObject = JSON.from(postMethod.getResponseBodyAsString(1024)); + URI uri = new URIBuilder() + .setHost(TokenEndpoint) + .setPath(TokenServiceUri) + .setParameter("client_id", clientId) + .setParameter("client_secret", secret) + .setParameter("code", authorizationCode) + .setParameter("redirect_uri", URLEncoder.encode(returnURI, "UTF-8")) + .build(); + HttpPost postMethod = new HttpPost(uri); + CloseableHttpClient jsonClient = HttpClients.custom().build(); + // Debug.logInfo("GitHub get access token query string: " + postMethod.getURI(), module); + postMethod.setConfig(PassportUtil.StandardRequestConfig); + postMethod.setHeader(PassportUtil.ACCEPT_HEADER, "application/json"); + CloseableHttpResponse postResponse = jsonClient.execute(postMethod); + String responseString = new BasicResponseHandler().handleResponse(postResponse); + // Debug.logInfo("GitHub get access token response code: " + postResponse.getStatusLine().getStatusCode(), module); + // Debug.logInfo("GitHub get access token response content: " + responseString, module); + if (postResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { + // Debug.logInfo("Json Response from GitHub: " + responseString, module); + JSON jsonObject = JSON.from(responseString); JSONToMap jsonMap = new JSONToMap(); Map<String, Object> userMap = jsonMap.convert(jsonObject); accessToken = (String) userMap.get("access_token"); @@ -190,37 +197,29 @@ public class GitHubEvents { // Debug.logInfo("Generated Access Token : " + accessToken, module); // Debug.logInfo("Token Type: " + tokenType, module); } else { - String errMsg = UtilProperties.getMessage(resource, "GetOAuth2GitHubAccessTokenError", UtilMisc.toMap("error", postMethod.getResponseBodyAsString()), UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(resource, "GetOAuth2GitHubAccessTokenError", UtilMisc.toMap("error", responseString), UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } } catch (UnsupportedEncodingException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; - } catch (HttpException e) { - request.setAttribute("_ERROR_MESSAGE_", e.toString()); - return "error"; } catch (IOException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (ConversionException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; - } finally { - postMethod.releaseConnection(); - } + } catch (URISyntaxException e) { + request.setAttribute("_ERROR_MESSAGE_", e.toString()); + return "error"; + } // Get User Profile - GetMethod getMethod = new GetMethod(ApiEndpoint + UserApiUri); + HttpGet getMethod = new HttpGet(ApiEndpoint + UserApiUri); Map<String, Object> userInfo = null; try { userInfo = GitHubAuthenticator.getUserInfo(getMethod, accessToken, tokenType, UtilHttp.getLocale(request)); - } catch (HttpException e) { - request.setAttribute("_ERROR_MESSAGE_", e.toString()); - return "error"; - } catch (IOException e) { - request.setAttribute("_ERROR_MESSAGE_", e.toString()); - return "error"; } catch (AuthenticatorException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; @@ -285,12 +284,12 @@ public class GitHubEvents { String userLoginId = authn.createUser(userInfo); userLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", userLoginId), false); } - String password = PassportUtil.randomString(); + String autoPassword = RandomStringUtils.randomAlphanumeric(Integer.parseInt(EntityUtilProperties.getPropertyValue("security", "password.length.min", "5", delegator))); boolean useEncryption = "true".equals(UtilProperties.getPropertyValue("security", "password.encrypt")); - userLogin.set("currentPassword", useEncryption ? HashCrypt.digestHash(LoginServices.getHashType(), null, password) : password); + userLogin.set("currentPassword", useEncryption ? HashCrypt.digestHash(LoginServices.getHashType(), null, autoPassword) : autoPassword); userLogin.store(); request.setAttribute("USERNAME", userLogin.getString("userLoginId")); - request.setAttribute("PASSWORD", password); + request.setAttribute("PASSWORD", autoPassword); } catch (GenericEntityException e) { Debug.logError(e.getMessage(), module); request.setAttribute("_ERROR_MESSAGE_", e.toString()); Modified: ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/event/LinkedInEvents.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/event/LinkedInEvents.java?rev=1735021&r1=1735020&r2=1735021&view=diff ============================================================================== --- ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/event/LinkedInEvents.java (original) +++ ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/event/LinkedInEvents.java Tue Mar 15 06:06:33 2016 @@ -20,6 +20,8 @@ package org.ofbiz.passport.event; import java.io.IOException; import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Map; @@ -29,13 +31,15 @@ import javax.servlet.http.HttpServletReq import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.ParserConfigurationException; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.httpclient.cookie.CookiePolicy; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.methods.PostMethod; -import org.apache.commons.httpclient.params.HttpMethodParams; +import org.apache.commons.lang.RandomStringUtils; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.impl.client.BasicResponseHandler; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; import org.ofbiz.passport.user.LinkedInAuthenticator; import org.ofbiz.passport.util.PassportUtil; import org.ofbiz.base.conversion.ConversionException; @@ -53,6 +57,7 @@ import org.ofbiz.entity.Delegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.util.EntityUtil; +import org.ofbiz.entity.util.EntityUtilProperties; import org.ofbiz.product.store.ProductStoreWorker; import org.ofbiz.service.LocalDispatcher; import org.w3c.dom.Document; @@ -164,58 +169,55 @@ public class LinkedInEvents { // Use the authorization code to obtain an access token String accessToken = null; - HttpClient jsonClient = new HttpClient(); - PostMethod postMethod = new PostMethod(TokenEndpoint + TokenServiceUri); try { - HttpMethodParams params = new HttpMethodParams(); - String queryString = "client_id=" + clientId - + "&client_secret=" + secret - + "&grant_type=authorization_code" - + "&code=" + authorizationCode - + "&redirect_uri=" + URLEncoder.encode(returnURI, "UTF-8"); - // Debug.logInfo("LinkedIn get access token query string: " + queryString, module); - postMethod.setQueryString(queryString); - params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); - postMethod.setParams(params); - jsonClient.executeMethod(postMethod); - // Debug.logInfo("LinkedIn get access token response code: " + postMethod.getStatusCode(), module); - // Debug.logInfo("LinkedIn get access token response content: " + postMethod.getResponseBodyAsString(1024), module); - if (postMethod.getStatusCode() == HttpStatus.SC_OK) { - // Debug.logInfo("Json Response from LinkedIn: " + postMethod.getResponseBodyAsString(1024), module); - JSON jsonObject = JSON.from(postMethod.getResponseBodyAsString(1024)); + URI uri = new URIBuilder() + .setHost(TokenEndpoint) + .setPath(TokenServiceUri) + .setParameter("client_id", clientId) + .setParameter("client_secret", secret) + .setParameter("grant_type", "authorization_code") + .setParameter("code", authorizationCode) + .setParameter("redirect_uri", URLEncoder.encode(returnURI, "UTF-8")) + .build(); + HttpPost postMethod = new HttpPost(uri); + CloseableHttpClient jsonClient = HttpClients.custom().build(); + // Debug.logInfo("LinkedIn get access token query string: " + postMethod.getURI(), module); + postMethod.setConfig(PassportUtil.StandardRequestConfig); + CloseableHttpResponse postResponse = jsonClient.execute(postMethod); + String responseString = new BasicResponseHandler().handleResponse(postResponse); + // Debug.logInfo("LinkedIn get access token response code: " + postResponse.getStatusLine().getStatusCode(), module); + // Debug.logInfo("LinkedIn get access token response content: " + responseString, module); + if (postResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { + // Debug.logInfo("Json Response from LinkedIn: " + responseString, module); + JSON jsonObject = JSON.from(responseString); JSONToMap jsonMap = new JSONToMap(); Map<String, Object> userMap = jsonMap.convert(jsonObject); accessToken = (String) userMap.get("access_token"); // Debug.logInfo("Generated Access Token : " + accessToken, module); } else { - String errMsg = UtilProperties.getMessage(resource, "GetOAuth2LinkedInAccessTokenError", UtilMisc.toMap("error", postMethod.getResponseBodyAsString()), UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(resource, "GetOAuth2LinkedInAccessTokenError", UtilMisc.toMap("error", responseString), UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } } catch (UnsupportedEncodingException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; - } catch (HttpException e) { - request.setAttribute("_ERROR_MESSAGE_", e.toString()); - return "error"; } catch (IOException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (ConversionException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; - } finally { - postMethod.releaseConnection(); - } + } catch (URISyntaxException e) { + request.setAttribute("_ERROR_MESSAGE_", e.toString()); + return "error"; + } // Get User Profile - GetMethod getMethod = new GetMethod(TokenEndpoint + UserApiUri + "?oauth2_access_token=" + accessToken); + HttpGet getMethod = new HttpGet(TokenEndpoint + UserApiUri + "?oauth2_access_token=" + accessToken); Document userInfo = null; try { userInfo = LinkedInAuthenticator.getUserInfo(getMethod, UtilHttp.getLocale(request)); - } catch (HttpException e) { - request.setAttribute("_ERROR_MESSAGE_", e.toString()); - return "error"; } catch (IOException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; @@ -289,12 +291,12 @@ public class LinkedInEvents { String userLoginId = authn.createUser(userInfo); userLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", userLoginId), false); } - String password = PassportUtil.randomString(); + String autoPassword = RandomStringUtils.randomAlphanumeric(Integer.parseInt(EntityUtilProperties.getPropertyValue("security", "password.length.min", "5", delegator))); boolean useEncryption = "true".equals(UtilProperties.getPropertyValue("security", "password.encrypt")); - userLogin.set("currentPassword", useEncryption ? HashCrypt.digestHash(LoginServices.getHashType(), null, password) : password); + userLogin.set("currentPassword", useEncryption ? HashCrypt.digestHash(LoginServices.getHashType(), null, autoPassword) : autoPassword); userLogin.store(); request.setAttribute("USERNAME", userLogin.getString("userLoginId")); - request.setAttribute("PASSWORD", password); + request.setAttribute("PASSWORD", autoPassword); } catch (GenericEntityException e) { Debug.logError(e.getMessage(), module); request.setAttribute("_ERROR_MESSAGE_", e.toString()); Modified: ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/user/GitHubAuthenticator.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/user/GitHubAuthenticator.java?rev=1735021&r1=1735020&r2=1735021&view=diff ============================================================================== --- ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/user/GitHubAuthenticator.java (original) +++ ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/user/GitHubAuthenticator.java Tue Mar 15 06:06:33 2016 @@ -27,12 +27,6 @@ import java.sql.Timestamp; import javax.transaction.Transaction; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.httpclient.cookie.CookiePolicy; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.params.HttpMethodParams; import org.ofbiz.passport.event.GitHubEvents; import org.ofbiz.passport.user.GitHubUserGroupMapper; import org.ofbiz.passport.util.PassportUtil; @@ -47,6 +41,13 @@ import org.ofbiz.entity.GenericEntityExc import org.ofbiz.entity.transaction.TransactionUtil; import org.ofbiz.entity.transaction.GenericTransactionException; import org.ofbiz.entity.util.EntityUtil; +import org.apache.http.HttpStatus; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.BasicResponseHandler; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; import org.ofbiz.base.conversion.ConversionException; import org.ofbiz.base.conversion.JSONConverters.JSONToMap; import org.ofbiz.base.lang.JSON; @@ -98,7 +99,7 @@ public class GitHubAuthenticator impleme */ public boolean authenticate(String userLoginId, String password, boolean isServiceAuth) throws AuthenticatorException { Map<String, Object> user = null; - GetMethod getMethod = null; + HttpGet getMethod = null; try { GenericValue userLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", userLoginId), false); String externalAuthId = userLogin.getString("externalAuthId"); @@ -107,16 +108,12 @@ public class GitHubAuthenticator impleme String accessToken = gitHubUser.getString("accessToken"); String tokenType = gitHubUser.getString("tokenType"); if (UtilValidate.isNotEmpty(accessToken)) { - getMethod = new GetMethod(GitHubEvents.ApiEndpoint + GitHubEvents.UserApiUri); + getMethod = new HttpGet(GitHubEvents.ApiEndpoint + GitHubEvents.UserApiUri); user = GitHubAuthenticator.getUserInfo(getMethod, accessToken, tokenType, Locale.getDefault()); } } } catch (GenericEntityException e) { throw new AuthenticatorException(e.getMessage(), e); - } catch (HttpException e) { - throw new AuthenticatorException(e.getMessage(), e); - } catch (IOException e) { - throw new AuthenticatorException(e.getMessage(), e); } catch (AuthenticatorException e) { throw new AuthenticatorException(e.getMessage(), e); } finally { @@ -208,7 +205,7 @@ public class GitHubAuthenticator impleme private Map<String, Object> getGitHubUserinfo(String userLoginId) throws AuthenticatorException { Map<String, Object> user = null; - GetMethod getMethod = null; + HttpGet getMethod = null; try { GenericValue userLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", userLoginId), false); String externalAuthId = userLogin.getString("externalAuthId"); @@ -217,22 +214,14 @@ public class GitHubAuthenticator impleme String accessToken = gitHubUser.getString("accessToken"); String tokenType = gitHubUser.getString("tokenType"); if (UtilValidate.isNotEmpty(accessToken)) { - getMethod = new GetMethod(GitHubEvents.ApiEndpoint + GitHubEvents.UserApiUri); + getMethod = new HttpGet(GitHubEvents.ApiEndpoint + GitHubEvents.UserApiUri); user = getUserInfo(getMethod, accessToken, tokenType, Locale.getDefault()); } } } catch (GenericEntityException e) { throw new AuthenticatorException(e.getMessage(), e); - } catch (HttpException e) { - throw new AuthenticatorException(e.getMessage(), e); - } catch (IOException e) { - throw new AuthenticatorException(e.getMessage(), e); } catch (AuthenticatorException e) { throw new AuthenticatorException(e.getMessage(), e); - } finally { - if (getMethod != null) { - getMethod.releaseConnection(); - } } return user; } @@ -387,22 +376,36 @@ public class GitHubAuthenticator impleme return "true".equalsIgnoreCase(UtilProperties.getPropertyValue(props, "github.authenticator.enabled", "true")); } - public static Map<String, Object> getUserInfo(GetMethod getMethod, String accessToken, String tokenType, Locale locale) throws HttpException, IOException, AuthenticatorException { + public static Map<String, Object> getUserInfo(HttpGet httpGet, String accessToken, String tokenType, Locale locale) throws AuthenticatorException { JSON userInfo = null; - HttpClient jsonClient = new HttpClient(); - HttpMethodParams params = new HttpMethodParams(); - params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); - getMethod.setParams(params); - getMethod.setRequestHeader(PassportUtil.AUTHORIZATION_HEADER, tokenType + " " + accessToken); - getMethod.setRequestHeader(PassportUtil.ACCEPT_HEADER, "application/json"); - jsonClient.executeMethod(getMethod); - if (getMethod.getStatusCode() == HttpStatus.SC_OK) { - Debug.logInfo("Json Response from GitHub: " + getMethod.getResponseBodyAsString(), module); - userInfo = JSON.from(getMethod.getResponseBodyAsString()); - } else { - String errMsg = UtilProperties.getMessage(resource, "GetOAuth2AccessTokenError", UtilMisc.toMap("error", getMethod.getResponseBodyAsString()), locale); - throw new AuthenticatorException(errMsg); - } + httpGet.setConfig(PassportUtil.StandardRequestConfig); + CloseableHttpClient jsonClient = HttpClients.custom().build(); + httpGet.setHeader(PassportUtil.AUTHORIZATION_HEADER, tokenType + " " + accessToken); + httpGet.setHeader(PassportUtil.ACCEPT_HEADER, "application/json"); + CloseableHttpResponse getResponse = null; + try { + getResponse = jsonClient.execute(httpGet); + String responseString = new BasicResponseHandler().handleResponse(getResponse); + if (getResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { + // Debug.logInfo("Json Response from GitHub: " + responseString, module); + userInfo = JSON.from(responseString); + } else { + String errMsg = UtilProperties.getMessage(resource, "GetOAuth2AccessTokenError", UtilMisc.toMap("error", responseString), locale); + throw new AuthenticatorException(errMsg); + } + } catch (ClientProtocolException e) { + throw new AuthenticatorException(e.getMessage()); + } catch (IOException e) { + throw new AuthenticatorException(e.getMessage()); + } finally { + if (getResponse != null) { + try { + getResponse.close(); + } catch (IOException e) { + // do nothing + } + } + } JSONToMap jsonMap = new JSONToMap(); Map<String, Object> userMap; try { Modified: ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/user/LinkedInAuthenticator.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/user/LinkedInAuthenticator.java?rev=1735021&r1=1735020&r2=1735021&view=diff ============================================================================== --- ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/user/LinkedInAuthenticator.java (original) +++ ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/user/LinkedInAuthenticator.java Tue Mar 15 06:06:33 2016 @@ -28,13 +28,14 @@ import java.sql.Timestamp; import javax.transaction.Transaction; import javax.xml.parsers.ParserConfigurationException; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.httpclient.cookie.CookiePolicy; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.params.HttpMethodParams; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.BasicResponseHandler; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; import org.ofbiz.passport.event.LinkedInEvents; +import org.ofbiz.passport.util.PassportUtil; import org.ofbiz.common.authentication.api.Authenticator; import org.ofbiz.common.authentication.api.AuthenticatorException; import org.ofbiz.service.LocalDispatcher; @@ -99,7 +100,7 @@ public class LinkedInAuthenticator imple */ public boolean authenticate(String userLoginId, String password, boolean isServiceAuth) throws AuthenticatorException { Document user = null; - GetMethod getMethod = null; + HttpGet getMethod = null; try { GenericValue userLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", userLoginId), false); String externalAuthId = userLogin.getString("externalAuthId"); @@ -107,14 +108,12 @@ public class LinkedInAuthenticator imple if (UtilValidate.isNotEmpty(linkedInUser)) { String accessToken = linkedInUser.getString("accessToken"); if (UtilValidate.isNotEmpty(accessToken)) { - getMethod = new GetMethod(LinkedInEvents.TokenEndpoint + LinkedInEvents.UserApiUri + "?oauth2_access_token=" + accessToken); + getMethod = new HttpGet(LinkedInEvents.TokenEndpoint + LinkedInEvents.UserApiUri + "?oauth2_access_token=" + accessToken); user = LinkedInAuthenticator.getUserInfo(getMethod, Locale.getDefault()); } } } catch (GenericEntityException e) { throw new AuthenticatorException(e.getMessage(), e); - } catch (HttpException e) { - throw new AuthenticatorException(e.getMessage(), e); } catch (IOException e) { throw new AuthenticatorException(e.getMessage(), e); } catch (AuthenticatorException e) { @@ -213,7 +212,7 @@ public class LinkedInAuthenticator imple private Document getLinkedInUserinfo(String userLoginId) throws AuthenticatorException { Document user = null; - GetMethod getMethod = null; + HttpGet getMethod = null; try { GenericValue userLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", userLoginId), false); String externalAuthId = userLogin.getString("externalAuthId"); @@ -221,14 +220,12 @@ public class LinkedInAuthenticator imple if (UtilValidate.isNotEmpty(linkedInUser)) { String accessToken = linkedInUser.getString("accessToken"); if (UtilValidate.isNotEmpty(accessToken)) { - getMethod = new GetMethod(LinkedInEvents.TokenEndpoint + LinkedInEvents.UserApiUri + "?oauth2_access_token=" + accessToken); + getMethod = new HttpGet(LinkedInEvents.TokenEndpoint + LinkedInEvents.UserApiUri + "?oauth2_access_token=" + accessToken); user = getUserInfo(getMethod, Locale.getDefault()); } } } catch (GenericEntityException e) { throw new AuthenticatorException(e.getMessage(), e); - } catch (HttpException e) { - throw new AuthenticatorException(e.getMessage(), e); } catch (IOException e) { throw new AuthenticatorException(e.getMessage(), e); } catch (AuthenticatorException e) { @@ -399,18 +396,17 @@ public class LinkedInAuthenticator imple return "true".equalsIgnoreCase(UtilProperties.getPropertyValue(props, "linked.authenticator.enabled", "true")); } - public static Document getUserInfo(GetMethod getMethod, Locale locale) throws HttpException, IOException, AuthenticatorException, SAXException, ParserConfigurationException { + public static Document getUserInfo(HttpGet httpGet, Locale locale) throws IOException, AuthenticatorException, SAXException, ParserConfigurationException { Document userInfo = null; - HttpClient jsonClient = new HttpClient(); - HttpMethodParams params = new HttpMethodParams(); - params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); - getMethod.setParams(params); - jsonClient.executeMethod(getMethod); - if (getMethod.getStatusCode() == HttpStatus.SC_OK) { - Debug.logInfo("Json Response from LinkedIn: " + getMethod.getResponseBodyAsString(), module); - userInfo = UtilXml.readXmlDocument(getMethod.getResponseBodyAsString()); + httpGet.setConfig(PassportUtil.StandardRequestConfig); + CloseableHttpClient jsonClient = HttpClients.custom().build(); + CloseableHttpResponse getResponse = jsonClient.execute(httpGet); + String responseString = new BasicResponseHandler().handleResponse(getResponse); + if (getResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { + // Debug.logInfo("Json Response from LinkedIn: " + responseString, module); + userInfo = UtilXml.readXmlDocument(responseString); } else { - String errMsg = UtilProperties.getMessage(resource, "GetOAuth2AccessTokenError", UtilMisc.toMap("error", getMethod.getResponseBodyAsString()), locale); + String errMsg = UtilProperties.getMessage(resource, "GetOAuth2AccessTokenError", UtilMisc.toMap("error", responseString), locale); throw new AuthenticatorException(errMsg); } return userInfo; Modified: ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/util/PassportUtil.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/util/PassportUtil.java?rev=1735021&r1=1735020&r2=1735021&view=diff ============================================================================== --- ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/util/PassportUtil.java (original) +++ ofbiz/trunk/specialpurpose/passport/src/org/ofbiz/passport/util/PassportUtil.java Tue Mar 15 06:06:33 2016 @@ -18,27 +18,12 @@ *******************************************************************************/ package org.ofbiz.passport.util; -import java.io.IOException; import java.net.InetAddress; -import java.net.Socket; import java.net.UnknownHostException; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; import javax.servlet.http.HttpServletRequest; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.ssl.SSLContextBuilder; -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; +import org.apache.http.client.config.CookieSpecs; +import org.apache.http.client.config.RequestConfig; import org.ofbiz.base.util.Debug; public class PassportUtil { @@ -105,6 +90,10 @@ public class PassportUtil { public static final String COMMON_APP_SECRET = "AppSecret"; + public static final RequestConfig StandardRequestConfig = RequestConfig.custom() + .setCookieSpec(CookieSpecs.STANDARD) + .build(); + protected PassportUtil() { // empty constructor } @@ -128,69 +117,4 @@ public class PassportUtil { } return prefix; } - - private static String randomString(int lo, int hi) { - int n = rand(lo, hi); - byte b[] = new byte[n]; - for (int i = 0; i < n; i++) { - b[i] = (byte)rand('a', 'z'); - } - return new String(b); - } - - private static int rand(int lo, int hi) { - java.util.Random rn = new java.util.Random(); - int n = hi - lo + 1; - int i = rn.nextInt() % n; - if (i < 0) - i = -i; - return lo + i; - } - - public static String randomString() { - return randomString(8, 15); - } - - public CloseableHttpClient getAllowAllHttpClient() { - try { - SSLContextBuilder builder = new SSLContextBuilder(); - builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); - SSLConnectionSocketFactory sf = new AllowAllSSLSocketFactory(builder.build()); - CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sf).build(); - return httpclient; - } catch (Exception e) { - return HttpClients.createDefault(); - } - } - - public class AllowAllSSLSocketFactory extends SSLConnectionSocketFactory { - SSLContext sslContext = SSLContext.getInstance("TLS"); - - public AllowAllSSLSocketFactory(SSLContext sslContext) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { - super(sslContext); - - TrustManager tm = new X509TrustManager() { - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { - } - - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { - } - - public X509Certificate[] getAcceptedIssuers() { - return null; - } - }; - - sslContext.init(null, new TrustManager[] { tm }, null); - } - - public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { - return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); - } - - public Socket createSocket() throws IOException { - return sslContext.getSocketFactory().createSocket(); - } - } - } \ No newline at end of file Modified: ofbiz/trunk/specialpurpose/solr/src/org/ofbiz/solr/SolrUtil.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/specialpurpose/solr/src/org/ofbiz/solr/SolrUtil.java?rev=1735021&r1=1735020&r2=1735021&view=diff ============================================================================== --- ofbiz/trunk/specialpurpose/solr/src/org/ofbiz/solr/SolrUtil.java (original) +++ ofbiz/trunk/specialpurpose/solr/src/org/ofbiz/solr/SolrUtil.java Tue Mar 15 06:06:33 2016 @@ -25,17 +25,11 @@ import java.util.List; import java.util.Map; import java.util.Set; -import javax.net.ssl.SSLContext; - import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.conn.ssl.NoopHostnameVerifier; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.ssl.SSLContexts; -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.solr.client.solrj.SolrQuery; @@ -47,8 +41,8 @@ import org.ofbiz.base.component.Componen import org.ofbiz.base.component.ComponentConfig.WebappInfo; import org.ofbiz.base.component.ComponentException; import org.ofbiz.base.util.Debug; -import org.ofbiz.base.util.FileUtil; import org.ofbiz.base.util.UtilGenerics; +import org.ofbiz.base.util.UtilHttp; import org.ofbiz.base.util.UtilProperties; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.entity.GenericEntityException; @@ -80,10 +74,6 @@ public final class SolrUtil { protected static final boolean trustSelfSignedCert = getTrustSelfSignedCert(); - protected SolrUtil() { - // empty constructor - } - public static String makeSolrWebappUrl() { final String solrWebappProtocol = UtilProperties.getPropertyValue(solrConfigName, "solr.webapp.protocol"); final String solrWebappDomainName = UtilProperties.getPropertyValue(solrConfigName, "solr.webapp.domainName"); @@ -255,7 +245,7 @@ public final class SolrUtil { QueryResponse returnMap = new QueryResponse(); try { // do the basic query - client = getInstance().getHttpSolrClient(solrIndexName); + client = getHttpSolrClient(solrIndexName); // create Query Object String query = "inStock[1 TO *]"; if (categoryId != null) @@ -298,36 +288,16 @@ public final class SolrUtil { return result; } - private CloseableHttpClient getAllowAllHttpClient() { - try { - // Trust own CA and all self-signed certs - SSLContext sslContext = SSLContexts.custom() - .loadTrustMaterial(FileUtil.getFile("component://base/config/ofbizssl.jks"), "changeit".toCharArray(), - new TrustSelfSignedStrategy()) - .build(); - // No host name verifier - SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( - sslContext, - NoopHostnameVerifier.INSTANCE); - CloseableHttpClient httpClient = HttpClients.custom() - .setSSLSocketFactory(sslsf) - .build(); - return httpClient; - } catch (Exception e) { - return HttpClients.createDefault(); - } - } - public static SolrUtil getInstance() { return new SolrUtil(); } - public HttpSolrClient getHttpSolrClient(String solrIndexName) throws ClientProtocolException, IOException { + public static HttpSolrClient getHttpSolrClient(String solrIndexName) throws ClientProtocolException, IOException { HttpClientContext httpContext = HttpClientContext.create(); CloseableHttpClient httpClient = null; if (trustSelfSignedCert) { - httpClient = getAllowAllHttpClient(); + httpClient = UtilHttp.getAllowAllHttpClient(); } else { httpClient = HttpClients.createDefault(); }