diff --git a/JSD-8967-需求确认书.docx b/JSD-8967-需求确认书.docx new file mode 100644 index 0000000..5013355 Binary files /dev/null and b/JSD-8967-需求确认书.docx differ diff --git a/README.md b/README.md index 10c836a..c2f0eb2 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,6 @@ -# open-JSD-8967 +# JSD-8967 -JSD-8967 app单点(基于时间戳和密钥加密签名) \ No newline at end of file +JSD-8967 app单点(基于时间戳和密钥加密签名)\ +免责说明:该源码为第三方爱好者提供,不保证源码和方案的可靠性,也不提供任何形式的源码教学指导和协助!\ +仅作为开发者学习参考使用!禁止用于任何商业用途!\ +为保护开发者隐私,开发者信息已隐去!若原开发者希望公开自己的信息,可联系hugh处理。 \ No newline at end of file diff --git a/plugin.xml b/plugin.xml new file mode 100644 index 0000000..eb5dc51 --- /dev/null +++ b/plugin.xml @@ -0,0 +1,20 @@ + + com.fr.plugin.jfsso + + yes + 1.0.1 + 10.0 + 2018-07-31 + wink + + + com.fr.plugin.jfsso + + + + + + + + \ No newline at end of file diff --git a/src/main/java/com/fr/plugin/jfsso/config/InitializeMonitor.java b/src/main/java/com/fr/plugin/jfsso/config/InitializeMonitor.java new file mode 100644 index 0000000..72b012d --- /dev/null +++ b/src/main/java/com/fr/plugin/jfsso/config/InitializeMonitor.java @@ -0,0 +1,21 @@ +package com.fr.plugin.jfsso.config; + +import com.fr.plugin.context.PluginContext; +import com.fr.plugin.observer.inner.AbstractPluginLifecycleMonitor; + +/** + * @author fr.open + * @version 10.0 + * Created by fr.open on 2018-12-04 + */ +public class InitializeMonitor extends AbstractPluginLifecycleMonitor { + @Override + public void afterRun(PluginContext pluginContext) { + PluginSimpleConfig.getInstance(); + } + + @Override + public void beforeStop(PluginContext pluginContext) { + + } +} diff --git a/src/main/java/com/fr/plugin/jfsso/config/PluginSimpleConfig.java b/src/main/java/com/fr/plugin/jfsso/config/PluginSimpleConfig.java new file mode 100644 index 0000000..29a9b17 --- /dev/null +++ b/src/main/java/com/fr/plugin/jfsso/config/PluginSimpleConfig.java @@ -0,0 +1,78 @@ +package com.fr.plugin.jfsso.config; + +import com.fr.config.*; +import com.fr.config.holder.Conf; +import com.fr.config.holder.factory.Holders; +import com.fr.intelli.record.Focus; +import com.fr.intelli.record.Original; +import com.fr.record.analyzer.EnableMetrics; + +@Visualization(category = "单点登录配置") +@EnableMetrics +public class PluginSimpleConfig extends DefaultConfiguration { + + private static volatile PluginSimpleConfig config = null; + + @Focus(id="com.fr.plugin.jfsso.config", text = "单点登录配置", source = Original.PLUGIN) + public static PluginSimpleConfig getInstance() { + if (config == null) { + config = ConfigContext.getConfigInstance(PluginSimpleConfig.class); + } + return config; + } + + @Identifier(value = "tokenStr", name = "token参数名", description = "token参数名", status = Status.SHOW) + private Conf tokenStr = Holders.simple("tokenid"); + + @Identifier(value = "tokenUrl", name = "获取用户信息链接", description = "获取用户信息链接", status = Status.SHOW) + private Conf tokenUrl = Holders.simple("http://localhost:18082/fr/user/"); + + @Identifier(value = "appkey", name = "app用加密key", description = "app用加密key", status = Status.SHOW) + private Conf appkey = Holders.simple("http://localhost:18082/fr/user/"); + + @Identifier(value = "frkey", name = "帆软用加密key", description = "帆软用加密key", status = Status.SHOW) + private Conf frkey = Holders.simple("http://localhost:18082/fr/user/"); + + public String getTokenStr() { + return tokenStr.get(); + } + + public void setTokenStr(String url) { + this.tokenStr.set(url); + } + + public String getTokenUrl() { + return tokenUrl.get(); + } + + public void setTokenUrl(String url) { + this.tokenUrl.set(url); + } + + public String getAppkey() { + return appkey.get(); + } + + public void setAppkey(String url) { + this.appkey.set(url); + } + + public String getFrkey() { + return frkey.get(); + } + + public void setFrkey(String url) { + this.frkey.set(url); + } + @Override + public Object clone() throws CloneNotSupportedException { + PluginSimpleConfig cloned = (PluginSimpleConfig) super.clone(); +// cloned.text = (Conf) text.clone(); +// cloned.count = (Conf) count.clone(); +// cloned.price = (Conf) price.clone(); +// cloned.time = (Conf) time.clone(); +// cloned.student = (Conf) student.clone(); + return cloned; + } + +} diff --git a/src/main/java/com/fr/plugin/jfsso/filter/SSOFilter.java b/src/main/java/com/fr/plugin/jfsso/filter/SSOFilter.java new file mode 100644 index 0000000..bf2e0f1 --- /dev/null +++ b/src/main/java/com/fr/plugin/jfsso/filter/SSOFilter.java @@ -0,0 +1,143 @@ +package com.fr.plugin.jfsso.filter; + +import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider; +import com.fr.json.JSONObject; +import com.fr.license.utils.JsonUtil; +import com.fr.plugin.context.PluginContexts; +import com.fr.plugin.jfsso.config.PluginSimpleConfig; +import com.fr.plugin.jfsso.utils.*; +import com.fr.record.analyzer.EnableMetrics; +import com.fr.stable.fun.Authorize; +import com.fr.third.org.apache.http.impl.cookie.BasicClientCookie; + +import javax.servlet.FilterChain; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.Calendar; +import java.util.Random; + + +@EnableMetrics +@Authorize(callSignKey = "com.fr.plugin.jfsso") +public class SSOFilter extends AbstractGlobalRequestFilterProvider { + + @Override + public String filterName() { + return "jfssoFilter"; + } + + @Override + public String[] urlPatterns() { + return new String[]{"/decision/*"}; + } + + @Override + public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain ){ + if(PluginContexts.currentContext().isAvailable()) { + PluginSimpleConfig psc = PluginSimpleConfig.getInstance(); + String tokenStr = psc.getTokenStr(); + //token + String tokenid = req.getParameter(tokenStr); + //时间戳 + String ts = req.getParameter("ts"); + //签名 + String sign = req.getParameter("sign"); + + if (Utils.isNotNullStr(tokenid)) { + String decrpt = EncryptUtils.aesDecrypt(tokenid,psc.getAppkey()); + String[] decrypt = decrpt.split("_"); + String jmts = decrypt[1]; + + if(!ts.equals(jmts)){ + ResponseUtils.failedResponse(res,"时间戳校验失败"); + return ; + } + + String shastr = decrypt[0]+"_"+ts; + String signstr =EncryptUtils.sha(shastr); + + if(!sign.equals(signstr)){ + ResponseUtils.failedResponse(res,"验签失败"); + return ; + } + + String username = getToken(tokenid, psc); + + FRUtils.FRLogInfo("username:" + username); + //登录 + FRUtils.login(req, res, username, ""); + } + } + + release(req,res,chain); + } + + /** + * 获取token + * @param tokenid + * @return + */ + private String getToken(String tokenid,PluginSimpleConfig psc) { + String tokenUrl = psc.getTokenUrl(); + + String random = getStringRandom(6); + String ts = String.valueOf(Calendar.getInstance().getTimeInMillis()); + String token = EncryptUtils.aesEncrypt(random+"_"+tokenid+"_"+ts,psc.getFrkey()); + String sign = EncryptUtils.sha(random+"_"+ts); + + tokenUrl += "?ts="+ts + "&saas_login_token="+token+"&sign="+sign; + BasicClientCookie[] cookies = new BasicClientCookie[1]; + BasicClientCookie bc = new BasicClientCookie("saas_login_token",tokenid); + bc.setPath("/"); + cookies[0] = bc; + String result = HttpUtils.HttpPostJson(tokenUrl,null,null,cookies); + + if(Utils.isNullStr(result)){ + return ""; + } + + JSONObject json = new JSONObject(result); + + if(json == null){ + return ""; + } + + String code = json.getString("code"); + + if(!code.equals("0")){ + return ""; + } + + return json.getJSONObject("result").getString("account"); + } + + //放行拦截器 + private void release(HttpServletRequest req, HttpServletResponse res, FilterChain chain) { + try{ + chain.doFilter(req,res); + }catch (Exception e){ + FRUtils.FRLogInfo("拦截失败"); + } + } + + public static String getStringRandom(int length) { + String val = ""; + Random random = new Random(); + //参数length,表示生成几位随机数 + for(int i = 0; i < length; i++) { + String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; + //输出字母还是数字 + if("char".equalsIgnoreCase(charOrNum)){ + //输出是大写字母还是小写字母 + int temp = random.nextInt(2) % 2 == 0 ? 65 : 97; + val += (char)(random.nextInt(26) + temp); + }else if("num".equalsIgnoreCase(charOrNum)) { + val += String.valueOf(random.nextInt(10)); + } + } + return val; + } + +} + diff --git a/src/main/java/com/fr/plugin/jfsso/utils/EncryptUtils.java b/src/main/java/com/fr/plugin/jfsso/utils/EncryptUtils.java new file mode 100644 index 0000000..4d018e3 --- /dev/null +++ b/src/main/java/com/fr/plugin/jfsso/utils/EncryptUtils.java @@ -0,0 +1,262 @@ +package com.fr.plugin.jfsso.utils; + +import com.fr.log.FineLoggerFactory; +import sun.misc.BASE64Decoder; +import sun.misc.BASE64Encoder; + +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.DESKeySpec; +import java.io.IOException; +import java.security.MessageDigest; +import java.security.SecureRandom; + +public class EncryptUtils { + + /** + * sha 加密 + * @param str + * @return + */ + public static String sha(String str){ + String sha256Str = ""; + + try { + MessageDigest sha256Deget = MessageDigest.getInstance("SHA-256"); + byte[] sha256Encode = sha256Deget.digest(str.getBytes()); + sha256Str = ByteToHexStr(sha256Encode); + }catch (Exception e){ + FineLoggerFactory.getLogger().info("FRLOG:SHA256加密异常:"+e.getMessage()); + } + + return sha256Str; + } + + /** + * byte数组转16进制字符串 + * @param bytes + * @return + */ + private static String ByteToHexStr(byte[] bytes) + { + String hexStr = ""; + + for(int i =0;i= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') + || c == '+' || c == '/' || c == '=') { + continue; + } + else { + return false; + } + } + + return true; + } + } + + /** + * des加密 + * @param datasource + * @param password + * @return + */ + public static String desEncrypt(String datasource, String password) { + try { + SecureRandom random = new SecureRandom(); + DESKeySpec desKey = new DESKeySpec(password.getBytes()); + // 创建一个密匙工厂,然后用它把DESKeySpec转换成 + SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); + SecretKey securekey = keyFactory.generateSecret(desKey); + // Cipher对象实际完成加密操作 + Cipher cipher = Cipher.getInstance("DES"); + // 用密匙初始化Cipher对象 + cipher.init(Cipher.ENCRYPT_MODE, securekey, random); + // 现在,获取数据并加密 + // 正式执行加密操作 + return base64Encode(cipher.doFinal(datasource.getBytes())); + } catch (Throwable e) { + FRUtils.FRLogInfo("des 加密异常 " + e.getMessage()); + } + + return null; + } + + /** + * des 解密 + * @param src + * @param password + * @return + * @throws Exception + */ + public static String desDecrypt(String src, String password) throws Exception { + // DES算法要求有一个可信任的随机数源 + SecureRandom random = new SecureRandom(); + // 创建一个DESKeySpec对象 + DESKeySpec desKey = new DESKeySpec(password.getBytes("UTF-8")); + // 创建一个密匙工厂 + SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); + // 将DESKeySpec对象转换成SecretKey对象 + SecretKey securekey = keyFactory.generateSecret(desKey); + // Cipher对象实际完成解密操作 + Cipher cipher = Cipher.getInstance("DES"); + // 用密匙初始化Cipher对象 + cipher.init(Cipher.DECRYPT_MODE, securekey, random); + // 真正开始解密操作 + return new String(cipher.doFinal(base64DecodeB(src))); + } +} diff --git a/src/main/java/com/fr/plugin/jfsso/utils/FRUtils.java b/src/main/java/com/fr/plugin/jfsso/utils/FRUtils.java new file mode 100644 index 0000000..836080f --- /dev/null +++ b/src/main/java/com/fr/plugin/jfsso/utils/FRUtils.java @@ -0,0 +1,167 @@ +package com.fr.plugin.jfsso.utils; + +import com.fr.decision.authority.AuthorityContext; +import com.fr.decision.authority.data.User; +import com.fr.decision.webservice.login.LogInOutResultInfo; +import com.fr.decision.webservice.utils.DecisionServiceConstants; +import com.fr.decision.webservice.v10.login.LoginService; +import com.fr.decision.webservice.v10.login.event.LogInOutEvent; +import com.fr.decision.webservice.v10.user.UserService; +import com.fr.event.EventDispatcher; +import com.fr.log.FineLoggerFactory; +import com.fr.stable.StringUtils; +import com.fr.stable.query.QueryFactory; +import com.fr.stable.query.restriction.RestrictionFactory; +import com.fr.web.utils.WebUtils; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import java.util.List; + +public class FRUtils { + /** + * 判断用户是否存在 + * @param userName + * @return + */ + public static boolean isUserExist(String userName){ + if (StringUtils.isEmpty(userName)) { + return false; + } else { + try { + List var1 = AuthorityContext.getInstance().getUserController().find(QueryFactory.create().addRestriction(RestrictionFactory.eq("userName", userName))); + return var1 != null && !var1.isEmpty(); + } catch (Exception var2) { + FineLoggerFactory.getLogger().error(var2.getMessage()); + return false; + } + } + } + + /** + * 判断是否登录FR + * @param req + * @return + */ + public static boolean isLogin(HttpServletRequest req){ + return LoginService.getInstance().isLogged(req); + } + + /** + * 帆软登录 + * @param httpServletRequest + * @param httpServletResponse + * @param userName + * @param url + */ + public static void login(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,String userName,String url){ + + FineLoggerFactory.getLogger().info("FRLOG:用户名:"+userName); + FineLoggerFactory.getLogger().info("FRLOG:跳转链接:"+url); + + + //判断用户名是否为空 + if(!Utils.isNullStr(userName)){ + if(isUserExist(userName)){ + String FRToken = ""; + + try { + HttpSession session = httpServletRequest.getSession(true); + + FRToken = LoginService.getInstance().login(httpServletRequest, httpServletResponse, userName); + + httpServletRequest.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME,FRToken); + + session.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME, FRToken); + EventDispatcher.fire(LogInOutEvent.LOGIN,new LogInOutResultInfo(httpServletRequest,httpServletResponse,userName,true)); + FineLoggerFactory.getLogger().info("FRLOG:登陆成功!"); + + if(!Utils.isNullStr(url)){ + httpServletResponse.sendRedirect(url); + } + } catch (Exception e) { + ResponseUtils.failedResponse(httpServletResponse,"登录异常,请联系管理员!"); + FineLoggerFactory.getLogger().info("FRLOG:登录异常,请联系管理员!"); + FineLoggerFactory.getLogger().info("FRLOGException:"+e.getMessage()); + } + }else{ + ResponseUtils.failedResponse(httpServletResponse,"用户在报表系统中不存在!"); + FineLoggerFactory.getLogger().info("FRLOG:用户在报表系统中不存在!"); + } + }else{ + ResponseUtils.failedResponse(httpServletResponse,"用户名不能为空!"); + FineLoggerFactory.getLogger().info("FRLOG:用户名不能为空!"); + } + } + + /** + * + * @param httpServletRequest + * @param httpServletResponse + */ + public static void logout(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) + { + if(!isLogin(httpServletRequest)){ + return ; + } + + try { + LoginService.getInstance().logout(httpServletRequest,httpServletResponse); + } catch (Exception e) { + ResponseUtils.failedResponse(httpServletResponse,"登出异常,请联系管理员!"); + FineLoggerFactory.getLogger().info("FRLOG:登出异常,请联系管理员!"); + FineLoggerFactory.getLogger().info("FRLOGException:"+e.getMessage()); + } + } + + /** + * 打印FR日志 + * @param message + */ + public static void FRLogInfo(String message){ + FineLoggerFactory.getLogger().info("FRLOG:"+message); + } + + /** + * 打印FR日志-error + * @param message + */ + public static void FRLogError(String message){ + FineLoggerFactory.getLogger().error("FRLOG:"+message); + } + + + /** + * 根据用户名获取用户信息 + * @param userName + * @return + */ + public static User getFRUserByUserName(String userName){ + try { + return UserService.getInstance().getUserByUserName(userName); + } catch (Exception e) { + FRLogInfo("获取用户信息异常:"+e.getMessage()); + } + + return null; + } + + /** + * 解密FR密码 + * @param password + * @return + */ +// public static String decryptFRPsd(String password){ +// FRLogInfo("解密密码:"+password); +// return TransmissionTool.decrypt(password); +// } + + /** + * 获取带参数的访问链接 + * @return + */ + public static String getAllUrl(HttpServletRequest httpServletRequest){ + return WebUtils.getOriginalURL(httpServletRequest); + } +} diff --git a/src/main/java/com/fr/plugin/jfsso/utils/HttpUtils.java b/src/main/java/com/fr/plugin/jfsso/utils/HttpUtils.java new file mode 100644 index 0000000..29f71b3 --- /dev/null +++ b/src/main/java/com/fr/plugin/jfsso/utils/HttpUtils.java @@ -0,0 +1,251 @@ +package com.fr.plugin.jfsso.utils; + +import com.fr.log.FineLoggerFactory; +import com.fr.third.org.apache.http.HttpEntity; +import com.fr.third.org.apache.http.HttpResponse; +import com.fr.third.org.apache.http.HttpStatus; +import com.fr.third.org.apache.http.NameValuePair; +import com.fr.third.org.apache.http.client.CookieStore; +import com.fr.third.org.apache.http.client.entity.UrlEncodedFormEntity; +import com.fr.third.org.apache.http.client.methods.HttpGet; +import com.fr.third.org.apache.http.client.methods.HttpPost; +import com.fr.third.org.apache.http.conn.ssl.NoopHostnameVerifier; +import com.fr.third.org.apache.http.entity.StringEntity; +import com.fr.third.org.apache.http.impl.client.BasicCookieStore; +import com.fr.third.org.apache.http.impl.client.CloseableHttpClient; +import com.fr.third.org.apache.http.impl.client.HttpClients; +import com.fr.third.org.apache.http.impl.cookie.BasicClientCookie; +import com.fr.third.org.apache.http.message.BasicNameValuePair; +import com.fr.third.org.apache.http.ssl.SSLContexts; +import com.fr.third.org.apache.http.ssl.TrustStrategy; +import com.fr.third.org.apache.http.util.EntityUtils; + +import javax.net.ssl.SSLContext; +import javax.servlet.http.Cookie; +import java.io.UnsupportedEncodingException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class HttpUtils { + /** + * httpGet请求 + * @param url + * @return + */ + public static String get(String url,BasicClientCookie[] cookies,Map header){ + FineLoggerFactory.getLogger().info("FRLOG:HttpUtils.get--url:"+url); + + //创建httpClient + CloseableHttpClient httpclient = createHttpClient(cookies); + + HttpGet getMethod = new HttpGet(url); + + if(header != null && header.size() > 0){ + Set keySet = header.keySet(); + + for(String key : keySet){ + getMethod.setHeader(key,header.get(key)); + } + } + + try { + HttpResponse response = httpclient.execute(getMethod); + int status =response.getStatusLine().getStatusCode(); + HttpEntity entity = response.getEntity(); + String returnResult = EntityUtils.toString(entity, "utf-8"); + + FineLoggerFactory.getLogger().info("FRLOG:HttpUtils.get--status:"+status); + FineLoggerFactory.getLogger().info("FRLOG:HttpUtils.get--returnResult:"+returnResult); + + if (status == HttpStatus.SC_OK) { + return returnResult; + } + } catch (Exception e) { + FineLoggerFactory.getLogger().info("FRLOG:HttpUtils.get--exception:"+e.getMessage()); + } + + return ""; + } + + /** + * HttpPost请求 + * @param postMethod + * @return + */ + private static String HttpPost2(HttpPost postMethod,BasicClientCookie[] cookies){ + CloseableHttpClient httpclient = createHttpClient(cookies); + + try { + HttpResponse response = httpclient.execute(postMethod); + int status = response.getStatusLine().getStatusCode(); + HttpEntity entity = response.getEntity(); + String returnResult = EntityUtils.toString(entity, "utf-8"); + FineLoggerFactory.getLogger().info("FRLOG:HttpPost:status:"+status); + FineLoggerFactory.getLogger().info("FRLOG:HttpPost:returnResult:"+returnResult); + + if (status == HttpStatus.SC_OK) { + return returnResult; + } + } catch (Exception e) { + FineLoggerFactory.getLogger().info("FRLOG:HttpPost:exception:"+e.getMessage()); + } + + return ""; + } + + /** + * HttpPost请求 + * @param postMethod + * @return + */ + private static String HttpPost(HttpPost postMethod){ + CloseableHttpClient httpclient = createHttpClient(null); + + try { + HttpResponse response = httpclient.execute(postMethod); + int status = response.getStatusLine().getStatusCode(); + HttpEntity entity = response.getEntity(); + String returnResult = EntityUtils.toString(entity, "utf-8"); + FineLoggerFactory.getLogger().info("FRLOG:HttpPost:status:"+status); + FineLoggerFactory.getLogger().info("FRLOG:HttpPost:returnResult:"+returnResult); + + if (status == HttpStatus.SC_OK) { + return returnResult; + } + } catch (Exception e) { + FineLoggerFactory.getLogger().info("FRLOG:HttpPost:exception:"+e.getMessage()); + } + + return ""; + } + + public static String HttpPostXML(String url, String xmlParam){ + FineLoggerFactory.getLogger().info("FRLOG:HttpPostXML:url:"+url); + + HttpPost postMethod = new HttpPost(url); + + postMethod.setHeader("Content-type", "text/html"); + HttpEntity entity2 = null; + try { + entity2 = new StringEntity(xmlParam); + } catch (UnsupportedEncodingException e) { + FineLoggerFactory.getLogger().info("FRLOG:HttpPostXML:参数异常:"+e.getMessage()); + return ""; + } + + postMethod.setEntity(entity2); + + return HttpPost(postMethod); + } + + public static String HttpPostJson(String url, String param,Map header,BasicClientCookie[] cookies){ + FineLoggerFactory.getLogger().info("FRLOG:HttpPostJSON:url:"+url); + + HttpPost postMethod = new HttpPost(url); + + postMethod.setHeader("Content-Type","application/json"); + + if(header != null && header.size() > 0){ + Set keySet = header.keySet(); + + for(String key : keySet){ + postMethod.setHeader(key,header.get(key)); + } + } + + if(!Utils.isNullStr(param)){ + HttpEntity entity2 = null; + try { + entity2 = new StringEntity(param); + } catch (UnsupportedEncodingException e) { + FineLoggerFactory.getLogger().info("FRLOG:HttpPostJSON:参数异常:"+e.getMessage()); + return ""; + } + + postMethod.setEntity(entity2); + } + + return HttpPost2(postMethod,cookies); + } + + public static String HttpPostWWWForm(String url, Map header,Map param){ + FineLoggerFactory.getLogger().info("FRLOG:HttpWWWForm:url:"+url); + + HttpPost postMethod = new HttpPost(url); + + if(header != null && header.size() > 0){ + Set keySet = header.keySet(); + + for(String key : keySet){ + postMethod.setHeader(key,header.get(key)); + } + } + + if(param != null && param.size() > 0){ + List params = new ArrayList(param.size()); + + for(Map.Entry map : param.entrySet()){ + params.add(new BasicNameValuePair(map.getKey(), map.getValue())); + } + + try { + postMethod.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); + } catch (UnsupportedEncodingException e) { + FineLoggerFactory.getLogger().info("FRLOG:HttpWWWForm:异常:"+e.getMessage()); + return ""; + } + } + + return HttpPost(postMethod); + } + + private static CloseableHttpClient createHttpClient(BasicClientCookie[] cookies){ + + SSLContext sslContext = null; + try { + sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() { + @Override + public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { + return true; + } + }).build(); + } catch (Exception e) { + FRUtils.FRLogInfo("exception:"+e.getMessage()); + } + + CloseableHttpClient httpclient = null; + + if(cookies != null && cookies.length > 0){ + BasicCookieStore cookieStore = cookieToCookieStore(cookies); + + httpclient = HttpClients.custom().setSslcontext(sslContext). + setSSLHostnameVerifier(new NoopHostnameVerifier()).setDefaultCookieStore(cookieStore).build(); + } + else{ + httpclient = HttpClients.custom().setSslcontext(sslContext). + setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); + } + + return httpclient; + } + + /** + * cookies转cookieStore + * @param cookies + * @return + */ + public static BasicCookieStore cookieToCookieStore(BasicClientCookie[] cookies){ + BasicCookieStore cookieStore = new BasicCookieStore(); + + if(cookies != null && cookies.length>0){ + for(BasicClientCookie cookie : cookies){ + cookieStore.addCookie(cookie); + } + } + return cookieStore; + } +} diff --git a/src/main/java/com/fr/plugin/jfsso/utils/ResponseUtils.java b/src/main/java/com/fr/plugin/jfsso/utils/ResponseUtils.java new file mode 100644 index 0000000..1443ca8 --- /dev/null +++ b/src/main/java/com/fr/plugin/jfsso/utils/ResponseUtils.java @@ -0,0 +1,94 @@ +package com.fr.plugin.jfsso.utils; + +import com.fr.json.JSONObject; +import com.fr.log.FineLoggerFactory; +import com.fr.web.utils.WebUtils; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.PrintWriter; + +public class ResponseUtils { + private static final int SUCCESS = 200; + private static final int FAILED = -1; + + public static void successResponse(HttpServletResponse res, String body) { + response(res, body, SUCCESS); + } + + public static void failedResponse(HttpServletResponse res, String body) { + response(res, body, FAILED); + } + + private static void response(HttpServletResponse res, String body, int code) { + JSONObject object = new JSONObject(); + PrintWriter pw; + try { + object.put("code", code); + object.put("data", body); + pw = WebUtils.createPrintWriter(res); + } catch (Exception e) { + FineLoggerFactory.getLogger().info(e.getMessage()); + return; + } + res.setContentType("application/json;charset=utf-8"); + String result = object.toString(); + pw.println(result); + pw.flush(); + pw.close(); + } + + public static void response(HttpServletResponse res,JSONObject json){ + PrintWriter pw; + try { + pw = WebUtils.createPrintWriter(res); + } catch (Exception e) { + FineLoggerFactory.getLogger().info(e.getMessage()); + return; + } + res.setContentType("application/json;charset=utf-8"); + String result = json.toString(); + pw.println(result); + pw.flush(); + pw.close(); + } + + public static void responseXml(HttpServletResponse res,String xml){ + PrintWriter pw; + try { + pw = WebUtils.createPrintWriter(res); + } catch (Exception e) { + FineLoggerFactory.getLogger().info(e.getMessage()); + return; + } + res.setContentType("text/xml;charset=utf-8"); + pw.println(xml); + pw.flush(); + pw.close(); + } + + public static void setCSRFHeader(HttpServletResponse httpServletResponse){ + httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); + httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,HEAD,PUT,PATCH"); + httpServletResponse.setHeader("Access-Control-Max-Age", "36000"); + httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,Authorization,authorization"); + } + + public static void responseJsonp(HttpServletRequest req, HttpServletResponse res, JSONObject json){ + PrintWriter pw; + try { + pw = WebUtils.createPrintWriter(res); + } catch (Exception e) { + FineLoggerFactory.getLogger().info(e.getMessage()); + return; + } + res.setContentType("text/javascript;charset=utf-8;charset=utf-8"); + String result = json.toString(); + + String jsonp=req.getParameter("callback"); + + pw.println(jsonp+"("+result+")"); + pw.flush(); + pw.close(); + } +} diff --git a/src/main/java/com/fr/plugin/jfsso/utils/Utils.java b/src/main/java/com/fr/plugin/jfsso/utils/Utils.java new file mode 100644 index 0000000..80e0ee1 --- /dev/null +++ b/src/main/java/com/fr/plugin/jfsso/utils/Utils.java @@ -0,0 +1,197 @@ +package com.fr.plugin.jfsso.utils; + +import com.fr.data.NetworkHelper; +import com.fr.json.JSONObject; +import com.fr.stable.CodeUtils; +import com.fr.stable.StringUtils; +import com.fr.third.org.apache.commons.codec.digest.DigestUtils; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import java.io.BufferedReader; +import java.net.URLEncoder; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class Utils { + + /** + * 判断字符串是否为空 + * @param str + * @return true 空字符串 false 非空字符串 + */ + public static boolean isNullStr(String str){ + return !(str != null && !str.isEmpty() && !"null".equals(str)); + } + + /** + * 判断字符串是否非空 + * @param str + * @return + */ + public static boolean isNotNullStr(String str){ + return !isNullStr(str); + } + + /** + * MD5加密 + * @param str + * @return + */ + public static String getMd5Str(String str) + { + return DigestUtils.md5Hex(str); + } + + /** + * 帆软shaEncode加密 + */ + + public static String shaEncode(String str){ + return CodeUtils.sha256Encode(str); + } + + /** + * 获取uuid + */ + public static String uuid(){ + return UUID.randomUUID().toString(); + } + + /** + * 替换空字符串 + * @param str + * @param replace + * @return + */ + public static String replaceNullStr(String str,String replace){ + if(isNullStr(str)){ + return replace; + } + + return str; + } + + /** + * 获取请求体 + * @param req + * @return + */ + public static JSONObject getRequestBody(HttpServletRequest req){ + StringBuffer sb = new StringBuffer(); + String line = null; + try { + BufferedReader reader = req.getReader(); + while ((line = reader.readLine()) != null) + sb.append(line); + } catch (Exception e) { + FRUtils.FRLogInfo("getRequestBody:exception:"+e.getMessage()); + } + //将空格和换行符替换掉避免使用反序列化工具解析对象时失败 + String jsonString = sb.toString().replaceAll("\\s","").replaceAll("\n",""); + + JSONObject json = new JSONObject(jsonString); + + return json; + } + + /** + * 获取ip + * @return + */ + public static String getIp(HttpServletRequest req){ + String realIp = req.getHeader("X-Real-IP"); + String fw = req.getHeader("X-Forwarded-For"); + if (StringUtils.isNotEmpty(fw) && !"unKnown".equalsIgnoreCase(fw)) { + int var3 = fw.indexOf(","); + return var3 != -1 ? fw.substring(0, var3) : fw; + } else { + fw = realIp; + if (StringUtils.isNotEmpty(realIp) && !"unKnown".equalsIgnoreCase(realIp)) { + return realIp; + } else { + if (StringUtils.isBlank(realIp) || "unknown".equalsIgnoreCase(realIp)) { + fw = req.getHeader("Proxy-Client-IP"); + } + + if (StringUtils.isBlank(fw) || "unknown".equalsIgnoreCase(fw)) { + fw = req.getHeader("WL-Proxy-Client-IP"); + } + + if (StringUtils.isBlank(fw) || "unknown".equalsIgnoreCase(fw)) { + fw = req.getHeader("HTTP_CLIENT_IP"); + } + + if (StringUtils.isBlank(fw) || "unknown".equalsIgnoreCase(fw)) { + fw = req.getHeader("HTTP_X_FORWARDED_FOR"); + } + + if (StringUtils.isBlank(fw) || "unknown".equalsIgnoreCase(fw)) { + fw = req.getRemoteAddr(); + } + + return fw; + } + } + } + + /** + * 根据key获取cookie + * @param req + * @return + */ + public static String getCookieByKey(HttpServletRequest req,String key){ + Cookie[] cookies = req.getCookies(); + String cookie = ""; + + if(cookies == null || cookies.length <=0){ + return ""; + } + + for(int i = 0; i < cookies.length; i++) { + Cookie item = cookies[i]; + if (item.getName().equalsIgnoreCase(key)) { + cookie = item.getValue(); + } + } + + FRUtils.FRLogInfo("cookie:"+cookie); + + return cookie; + } + + /** + * 判断是否是手机端的链接 + * @param req + * @return + */ + public static boolean isMobile(HttpServletRequest req) { + String[] mobileArray = {"iPhone", "iPad", "android", "windows phone", "xiaomi"}; + String userAgent = req.getHeader("user-agent"); + if (userAgent != null && userAgent.toUpperCase().contains("MOBILE")) { + for(String mobile : mobileArray) { + if(userAgent.toUpperCase().contains(mobile.toUpperCase())) { + return true; + } + } + } + return NetworkHelper.getDevice(req).isMobile(); + } + + /** + * 只编码中文 + * @param url + * @return + */ + public static String encodeCH(String url ){ + Matcher matcher = Pattern.compile("[\\u4e00-\\u9fa5]").matcher(url); + + while(matcher.find()){ + String chn = matcher.group(); + url = url.replaceAll(chn, URLEncoder.encode(chn)); + } + + return url; + } +}