diff --git a/README.md b/README.md index a550110..5c45a11 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,6 @@ # open-JSD-8709 -JSD-8709 jwt单点 \ No newline at end of file +JSD-8709 jwt单点\ +免责说明:该源码为第三方爱好者提供,不保证源码和方案的可靠性,也不提供任何形式的源码教学指导和协助!\ +仅作为开发者学习参考使用!禁止用于任何商业用途!\ +为保护开发者隐私,开发者信息已隐去!若原开发者希望公开自己的信息,可联系hugh处理。 \ No newline at end of file diff --git a/lib/commons-codec-1.15.jar b/lib/commons-codec-1.15.jar new file mode 100644 index 0000000..f14985a Binary files /dev/null and b/lib/commons-codec-1.15.jar differ diff --git a/lib/jackson-annotations-2.9.0.jar b/lib/jackson-annotations-2.9.0.jar new file mode 100644 index 0000000..c602d75 Binary files /dev/null and b/lib/jackson-annotations-2.9.0.jar differ diff --git a/lib/jackson-core-2.9.8.jar b/lib/jackson-core-2.9.8.jar new file mode 100644 index 0000000..362f1f3 Binary files /dev/null and b/lib/jackson-core-2.9.8.jar differ diff --git a/lib/jackson-databind-2.9.8.jar b/lib/jackson-databind-2.9.8.jar new file mode 100644 index 0000000..2d8687b Binary files /dev/null and b/lib/jackson-databind-2.9.8.jar differ diff --git a/lib/java-jwt-3.9.0.jar b/lib/java-jwt-3.9.0.jar new file mode 100644 index 0000000..a379579 Binary files /dev/null and b/lib/java-jwt-3.9.0.jar differ diff --git a/plugin.xml b/plugin.xml new file mode 100644 index 0000000..cd9b650 --- /dev/null +++ b/plugin.xml @@ -0,0 +1,24 @@ + + com.fr.plugin.rcsso + + yes + 1.0.14 + 10.0 + 2018-07-31 + fr.open + + + com.fr.plugin.rcsso + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/java/com/fr/plugin/rcsso/config/InitializeMonitor.java b/src/main/java/com/fr/plugin/rcsso/config/InitializeMonitor.java new file mode 100644 index 0000000..eb068f3 --- /dev/null +++ b/src/main/java/com/fr/plugin/rcsso/config/InitializeMonitor.java @@ -0,0 +1,21 @@ +package com.fr.plugin.rcsso.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/rcsso/config/PluginSimpleConfig.java b/src/main/java/com/fr/plugin/rcsso/config/PluginSimpleConfig.java new file mode 100644 index 0000000..1e1c38a --- /dev/null +++ b/src/main/java/com/fr/plugin/rcsso/config/PluginSimpleConfig.java @@ -0,0 +1,133 @@ +package com.fr.plugin.rcsso.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.xxw.config", text = "单点登录配置", source = Original.PLUGIN) + public static PluginSimpleConfig getInstance() { + if (config == null) { + config = ConfigContext.getConfigInstance(PluginSimpleConfig.class); + } + return config; + } + + @Identifier(value = "tokenStr", name = "参数名称", description = "参数名称", status = Status.SHOW) + private Conf tokenStr = Holders.simple("tokenid"); + + @Identifier(value = "pkey", name = "秘钥", description = "秘钥", status = Status.SHOW) + private Conf pkey = Holders.simple(""); + + @Identifier(value = "clientId", name = "clientId", description = "clientId", status = Status.SHOW) + private Conf clientId = Holders.simple(""); + + @Identifier(value = "secret", name = "secret", description = "secret", status = Status.SHOW) + private Conf secret = Holders.simple(""); + + @Identifier(value = "authurl", name = "authorize接口", description = "authorize接口", status = Status.SHOW) + private Conf authurl = Holders.simple(""); + + @Identifier(value = "token", name = "tokens接口", description = "tokens接口", status = Status.SHOW) + private Conf token = Holders.simple(""); + + @Identifier(value = "user", name = "获取用户信息接口", description = "获取用户信息接口", status = Status.SHOW) + private Conf user = Holders.simple(""); + + @Identifier(value = "logout", name = "单点登出接口", description = "单点登出接口", status = Status.SHOW) + private Conf logout = Holders.simple(""); + + @Identifier(value = "index", name = "FR首页", description = "FR首页", status = Status.SHOW) + private Conf index = Holders.simple(""); + + public String getTokenStr() { + return tokenStr.get(); + } + + public void setTokenStr(String url) { + this.tokenStr.set(url); + } + + public String getPkey() { + return pkey.get(); + } + + public void setPkey(String url) { + this.pkey.set(url); + } + + public String getClientId() { + return clientId.get(); + } + + public void setClientId(String url) { + this.clientId.set(url); + } + + public String getSecret() { + return secret.get(); + } + + public void setSecret(String url) { + this.secret.set(url); + } + + public String getAuthurl() { + return authurl.get(); + } + + public void setAuthurl(String url) { + this.authurl.set(url); + } + + public String getToken() { + return token.get(); + } + + public void setToken(String url) { + this.token.set(url); + } + + public String getUser() { + return user.get(); + } + + public void setUser(String url) { + this.user.set(url); + } + + public String getLogout() { + return logout.get(); + } + + public void setLogout(String url) { + this.logout.set(url); + } + + public String getIndex() { + return index.get(); + } + + public void setIndex(String url) { + this.index.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/rcsso/filter/SSOFilter.java b/src/main/java/com/fr/plugin/rcsso/filter/SSOFilter.java new file mode 100644 index 0000000..b552102 --- /dev/null +++ b/src/main/java/com/fr/plugin/rcsso/filter/SSOFilter.java @@ -0,0 +1,78 @@ +package com.fr.plugin.rcsso.filter; + +import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider; +import com.fr.plugin.context.PluginContexts; +import com.fr.plugin.rcsso.config.PluginSimpleConfig; +import com.fr.plugin.rcsso.utils.*; +import com.fr.plugin.transform.FunctionRecorder; +import com.fr.record.analyzer.EnableMetrics; +import com.fr.stable.fun.Authorize; + +import javax.servlet.FilterChain; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.net.URLDecoder; + +@EnableMetrics +@FunctionRecorder +@Authorize(callSignKey = "com.fr.plugin.rcsso") +public class SSOFilter extends AbstractGlobalRequestFilterProvider { + @Override + public String filterName() { + return "rcssoFilter"; + } + + @Override + public String[] urlPatterns() { + return new String[]{"/decision/*"}; + } + + @Override + public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain ){ + if(PluginContexts.currentContext().isAvailable()) { + String tokenStr = PluginSimpleConfig.getInstance().getTokenStr(); + String token = req.getParameter(tokenStr); + + FRUtils.FRLogInfo("tokenStr:"+tokenStr + ";token:"+token); + + if(Utils.isNullStr(token) || FRUtils.isLogin(req)){ + release(req,res,chain); + return ; + } + + String privateKey = PluginSimpleConfig.getInstance().getPkey(); + String userName = ""; + try { + if(Utils.isMobile(req)){ + FRUtils.FRLogInfo("mobile"); + userName = JwtUtil.getUsername(token); + }else{ + FRUtils.FRLogInfo("pc"); + userName = RSAUtil.decrypt(token,privateKey); + } + FRUtils.FRLogInfo("username "+userName); + } catch (Exception e) { + FRUtils.FRLogError("getUserName exception:"+e.getMessage()); + ResponseUtils.failedResponse(res,"解密用户名异常"); + } + + String url = FRUtils.getAllUrl(req); + url = url.substring(0,url.indexOf(url.contains("?token") ? "?token" : "&token")); + url = url.replace("http","https"); + //登录 + FRUtils.login(req,res,userName,url); + } + + release(req,res,chain); + } + + //放行拦截器 + private void release(HttpServletRequest req, HttpServletResponse res, FilterChain chain) { + try{ + chain.doFilter(req,res); + }catch (Exception e){ + FRUtils.FRLogInfo("拦截失败"); + } + } +} + diff --git a/src/main/java/com/fr/plugin/rcsso/handler/ExtendAttrHandlerProvider.java b/src/main/java/com/fr/plugin/rcsso/handler/ExtendAttrHandlerProvider.java new file mode 100644 index 0000000..0de16bc --- /dev/null +++ b/src/main/java/com/fr/plugin/rcsso/handler/ExtendAttrHandlerProvider.java @@ -0,0 +1,13 @@ +package com.fr.plugin.rcsso.handler; + +import com.fr.decision.fun.HttpHandler; +import com.fr.decision.fun.impl.AbstractHttpHandlerProvider; + +public class ExtendAttrHandlerProvider extends AbstractHttpHandlerProvider { + @Override + public HttpHandler[] registerHandlers() { + return new HttpHandler[]{ + new Login() + }; + } +} diff --git a/src/main/java/com/fr/plugin/rcsso/handler/Login.java b/src/main/java/com/fr/plugin/rcsso/handler/Login.java new file mode 100644 index 0000000..e43428a --- /dev/null +++ b/src/main/java/com/fr/plugin/rcsso/handler/Login.java @@ -0,0 +1,108 @@ +package com.fr.plugin.rcsso.handler; + +import com.fr.decision.fun.impl.BaseHttpHandler; +import com.fr.json.JSONObject; +import com.fr.plugin.rcsso.config.PluginSimpleConfig; +import com.fr.plugin.rcsso.utils.CipherUtils; +import com.fr.plugin.rcsso.utils.FRUtils; +import com.fr.plugin.rcsso.utils.HttpUtils; +import com.fr.plugin.rcsso.utils.Utils; +import com.fr.plugin.transform.FunctionRecorder; +import com.fr.third.springframework.web.bind.annotation.RequestMethod; +import org.nfunk.jep.function.Str; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.Map; + +@FunctionRecorder +public class Login extends BaseHttpHandler { + + + public Login() { + } + + @Override + public RequestMethod getMethod() { + return RequestMethod.GET; + } + + @Override + public String getPath() { + return "/sso"; + } + + @Override + public boolean isPublic() { + return true; + } + + @Override + public void handle(HttpServletRequest req, HttpServletResponse res) throws Exception { + PluginSimpleConfig psc = PluginSimpleConfig.getInstance(); + //获取请求参数 + String code = req.getParameter("code"); + String token = req.getParameter("token"); + String url = psc.getIndex()+"/url/sso"; + String username = ""; + + //插件跳转到认证中心返回code + if(Utils.isNotNullStr(code)){ + token = getToken(code,url,psc); + } + + if(Utils.isNotNullStr(token)){ + username = getUsername(token,psc); + } + + if(Utils.isNotNullStr(username)){ + FRUtils.login(req,res,username,psc.getIndex()); + return ; + } + + String redirecturl =psc.getAuthurl()+"?client_id="+psc.getClientId()+"&response_type=code&redirect_uri="+psc.getIndex()+ + "/url/sso&scope=UserProfile.me&state=xyz"; + + res.sendRedirect(redirecturl); + } + + private static String getUsername(String token,PluginSimpleConfig psc){ + String userurl = psc.getUser(); + Map header = new HashMap(); + header.put("Authorization",token); + String result = HttpUtils.get(userurl,null,header); + + if(Utils.isNullStr(result)){ + return ""; + } + + JSONObject json = new JSONObject(result); + + return json.getString("uid").toLowerCase(); + } + + private static String getToken(String code,String url,PluginSimpleConfig psc){ + String accessToken = ""; + String tokenurl = psc.getToken()+"?redirect_uri="+url+"&grant_type=authorization_code&code="+code; + + Map header = new HashMap(); + header.put("Authorization","Basic "+new String(CipherUtils.base64Encode(psc.getClientId()+":"+psc.getSecret())).trim()); + + String resutl = HttpUtils.HttpPostWWWForm(tokenurl,header,null); + JSONObject obj = new JSONObject(resutl); + accessToken = obj.getString("access_token"); + + return accessToken; + } + + +} + diff --git a/src/main/java/com/fr/plugin/rcsso/handler/URLAliasProvide.java b/src/main/java/com/fr/plugin/rcsso/handler/URLAliasProvide.java new file mode 100644 index 0000000..e3498c6 --- /dev/null +++ b/src/main/java/com/fr/plugin/rcsso/handler/URLAliasProvide.java @@ -0,0 +1,14 @@ +package com.fr.plugin.rcsso.handler; + +import com.fr.decision.fun.impl.AbstractURLAliasProvider; +import com.fr.decision.webservice.url.alias.URLAlias; +import com.fr.decision.webservice.url.alias.URLAliasFactory; + +public class URLAliasProvide extends AbstractURLAliasProvider { + @Override + public URLAlias[] registerAlias() { + return new URLAlias[]{ + URLAliasFactory.createPluginAlias("/sso","/sso",true), + }; + } +} diff --git a/src/main/java/com/fr/plugin/rcsso/logout/Logout.java b/src/main/java/com/fr/plugin/rcsso/logout/Logout.java new file mode 100644 index 0000000..7e711a5 --- /dev/null +++ b/src/main/java/com/fr/plugin/rcsso/logout/Logout.java @@ -0,0 +1,21 @@ +package com.fr.plugin.rcsso.logout; + +import com.fr.decision.fun.impl.AbstractLogInOutEventProvider; +import com.fr.decision.webservice.login.LogInOutResultInfo; +import com.fr.decision.webservice.v10.login.LoginService; +import com.fr.plugin.rcsso.config.PluginSimpleConfig; + +import javax.servlet.http.HttpSession; + +public class Logout extends AbstractLogInOutEventProvider { + + @Override + public String logoutAction(LogInOutResultInfo result) { + HttpSession session = result.getRequest().getSession(true); + LoginService.getInstance().crossDomainLogout(result.getRequest(),result.getResponse(),""); + session.invalidate(); + PluginSimpleConfig psc = PluginSimpleConfig.getInstance(); + return psc.getLogout()+"?end_url="+psc.getIndex()+"/url/sso"; + } +} + diff --git a/src/main/java/com/fr/plugin/rcsso/utils/CipherUtils.java b/src/main/java/com/fr/plugin/rcsso/utils/CipherUtils.java new file mode 100644 index 0000000..66b572a --- /dev/null +++ b/src/main/java/com/fr/plugin/rcsso/utils/CipherUtils.java @@ -0,0 +1,262 @@ +package com.fr.plugin.rcsso.utils; + +import com.fr.log.FineLoggerFactory; +import sun.misc.BASE64Decoder; +import sun.misc.BASE64Encoder; + +import javax.crypto.Cipher; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.DESKeySpec; +import javax.crypto.spec.SecretKeySpec; +import java.io.IOException; +import java.security.Key; +import java.security.MessageDigest; +import java.security.SecureRandom; + +/** + * 加解密工具类 + */ +public class CipherUtils { + /** + * 加密 + * + * @param datasource + * byte[] + * @param password + * String + * @return byte[] + */ + public static byte[] desEncrypt(byte[] 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 cipher.doFinal(datasource); + } catch (Throwable e) { + e.printStackTrace(); + } + + return null; + } + + /** + * 解密 + * + * @param src + * byte[] + * @param password + * String + * @return byte[] + * @throws Exception + */ + public static byte[] desDecrypt(byte[] 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 cipher.doFinal(src); + } + + /** + * 自定义一个key + **/ + public static byte[] getKey(String keyRule) { + Key key = null; + byte[] keyByte = keyRule.getBytes(); + // 创建一个空的八位数组,默认情况下为0 + byte[] byteTemp = new byte[8]; + // 将用户指定的规则转换成八位数组 + for (int i = 0; i < byteTemp.length && i < keyByte.length; i++) { + byteTemp[i] = keyByte[i]; + } + key = new SecretKeySpec(byteTemp, "DES"); + return key.getEncoded(); + + } + + /** + * 将16进制转换为二进制 + * + * @param hexStr + * @return + */ + public static byte[] parseHexStr2Byte(String hexStr) { + if (hexStr.length() < 1) return null; + byte[] result = new byte[hexStr.length() / 2]; + for (int i = 0; i < hexStr.length() / 2; i++) { + int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); + int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); + result[i] = (byte) (high * 16 + low); + } + return result; + } + + /*** + * 解密数据 + * @param decryptString + * @param decryptKey + * @return + * @throws Exception + */ + public static String decryptDES(String decryptString, String decryptKey) throws Exception { + SecretKeySpec key = new SecretKeySpec(getKey(decryptKey), "DES"); + Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); + cipher.init(Cipher.DECRYPT_MODE, key); + byte decryptedData[] = cipher.doFinal(parseHexStr2Byte(decryptString)); + return new String(decryptedData,"utf-8"); + } + + /** + * jdksha256加密 + * @param str + * @return + */ + public static String jdksha256(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; + } + } + public static void main(String[] args) throws Exception { +// String key = "z2bse2zh"; +// String key = "ajshcjzj"; +// String str = "男"; +//// +// byte[] a =desEncrypt(str.getBytes(),key); +//// System.out.println(new String(a)); +// String a1 = new BASE64Encoder().encodeBuffer(a); +//// +// System.out.println(a1); +//// +//// byte[] b = desDecrypt(a,key); +//// System.out.println(new String(b)); +// +// String key2 = "rdTK5iLsDFw="; +// byte[] b2 = desDecrypt(new BASE64Decoder().decodeBuffer(key2),"ajshcjzj"); +// System.out.println(new String(b2)); +// //密钥 +// String key = "z2bse2zh"; +// //解密数据 +// String encryDate = "DF2DF0F837C38A1233A8B1255B0532E36E9D29052873B7F8707936C025E2FE368B0A8919A93C8869"; +// String a = "ED33AD65CDBAEF49"; +// String result = decryptDES(a, key); +// +// System.out.println("result:" + result); +// System.out.println("result2:"+new String(decrypt(result.getBytes(),key))); + } +} diff --git a/src/main/java/com/fr/plugin/rcsso/utils/FRUtils.java b/src/main/java/com/fr/plugin/rcsso/utils/FRUtils.java new file mode 100644 index 0000000..8597045 --- /dev/null +++ b/src/main/java/com/fr/plugin/rcsso/utils/FRUtils.java @@ -0,0 +1,190 @@ +package com.fr.plugin.rcsso.utils; + +import com.fr.base.ServerConfig; +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.Cookie; +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); + writeToken2Cookie(httpServletResponse,FRToken,-1); + + 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:用户名不能为空!"); + } + } + + private static void writeToken2Cookie(HttpServletResponse var1, String var2, int var3) { + try { + if (StringUtils.isNotEmpty(var2)) { + Cookie var4 = new Cookie("fine_auth_token", var2); + long var5 = var3 == -2 ? 1209600000L : (long)var3; + var4.setMaxAge((int)var5); + var4.setPath(ServerConfig.getInstance().getCookiePath()); + var1.addCookie(var4); + Cookie var7 = new Cookie("fine_remember_login", String.valueOf(var3 == -2 ? -2 : -1)); + var7.setMaxAge((int)var5); + var7.setPath(ServerConfig.getInstance().getCookiePath()); + var1.addCookie(var7); + } else { + FineLoggerFactory.getLogger().error("empty token cannot save."); + } + } catch (Exception var8) { + FineLoggerFactory.getLogger().error(var8.getMessage(), var8); + } + + } + + /** + * + * @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/rcsso/utils/HttpUtils.java b/src/main/java/com/fr/plugin/rcsso/utils/HttpUtils.java new file mode 100644 index 0000000..9fa28af --- /dev/null +++ b/src/main/java/com/fr/plugin/rcsso/utils/HttpUtils.java @@ -0,0 +1,230 @@ +package com.fr.plugin.rcsso.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.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +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,Cookie[] 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 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){ + 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 HttpPost(postMethod); + } + + 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(Cookie[] 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){ + CookieStore 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 CookieStore cookieToCookieStore(Cookie[] cookies){ + CookieStore cookieStore = new BasicCookieStore(); + + if(cookies != null && cookies.length>0){ + for(Cookie cookie : cookies){ + BasicClientCookie cookie1 = new BasicClientCookie(cookie.getName(), cookie.getValue()); + cookieStore.addCookie(cookie1); + } + } + + return cookieStore; + } +} diff --git a/src/main/java/com/fr/plugin/rcsso/utils/JwtUtil.java b/src/main/java/com/fr/plugin/rcsso/utils/JwtUtil.java new file mode 100644 index 0000000..54a368b --- /dev/null +++ b/src/main/java/com/fr/plugin/rcsso/utils/JwtUtil.java @@ -0,0 +1,92 @@ +package com.fr.plugin.rcsso.utils; + +import java.util.Date; +import com.auth0.jwt.JWT; +import com.auth0.jwt.JWTVerifier; +import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.interfaces.DecodedJWT; + +/** + * JWT工具类 + * @author ibm + */ +public class JwtUtil +{ + /** + * 过期时间7天 + */ + private static final long EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000; + + /** + * 校验token是否正确 + * @param token 密钥 + * @param secret 用户的密码 + * @return 是否正确 + */ + public static boolean verify(String token, String username, String secret) + { + try + { + Algorithm algorithm = Algorithm.HMAC256(secret); + JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build(); + verifier.verify(token); + return true; + } + catch (Exception exception) + { + return false; + } + } + + /** + * 获得token中的信息无需secret解密也能获得 + * @return token中包含的用户名 + */ + public static String getUsername(String token) + { + try + { + DecodedJWT jwt = JWT.decode(token); + return jwt.getClaim("username").asString(); + } + catch (Exception e) + { + throw new RuntimeException("获取用户名出错,原因:"+e.getMessage(),e); + } + } + + /** + * 获得token中的信息无需secret解密也能获得 + * @return token中包含的用户ID + */ + public static long getUserId(String token) + { + try + { + DecodedJWT jwt = JWT.decode(token); + return jwt.getClaim("userId").asLong(); + } + catch (Exception e) + { + throw new RuntimeException("获取用户ID出错,原因:",e); + } + } + + /** + * 生成签名,指定时间后过期 + * @param username 用户名 + * @param secret 用户的密码 + * @return 加密的token + */ + public static String sign(String username, String secret,long userId,Long redisExpire) + { + Date date = new Date(System.currentTimeMillis() + redisExpire); + Algorithm algorithm = Algorithm.HMAC256(secret); + // 附带username信息 + return JWT.create().withClaim("username", username).withClaim("userId",userId).withExpiresAt(date).sign(algorithm); + } + + public static void main(String[] args) { + System.out.println(getUsername("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NDMyNjkwNDIsInVzZXJJZCI6MjkyMCwidXNlcm5hbWUiOiJsX2dvbmdkY3M1In0.fIje0LK23p-LRtED8J80Nt5cCqd1fDoK3NuZY2ogPyc")); + } +} \ No newline at end of file diff --git a/src/main/java/com/fr/plugin/rcsso/utils/RSAUtil.java b/src/main/java/com/fr/plugin/rcsso/utils/RSAUtil.java new file mode 100644 index 0000000..7a57332 --- /dev/null +++ b/src/main/java/com/fr/plugin/rcsso/utils/RSAUtil.java @@ -0,0 +1,45 @@ +package com.fr.plugin.rcsso.utils; + +import org.apache.commons.codec.binary.Base64; + +import javax.crypto.Cipher; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.security.KeyFactory; +import java.security.interfaces.RSAPrivateKey; +import java.security.spec.PKCS8EncodedKeySpec; + +public class RSAUtil { + public static void main(String[] args) throws Exception { + // 密文 +// String message = "aFnvaH3EvOQYX/1zRMwueZvaEG/Oghm4aJ25HtEhYIEQAuLUMRpN9rAfL8a6DWoQ93Cm6bBlfNIRQE0HvDnb897ClmL9tXC3 rGjO8P5RXAuCTywpLHJI/774 z1iXsIi 50YoTDCyt1oKm1z2vc5QBr8EV8ivNk56mFC/s7LqY="; + String message = URLDecoder.decode("G2xTxbkrjzgEA4YOryTOUYksyJX0uHnvrutmFgnZEtD291kuSI%2Bq5oEaetqBz%2BVBh3D4Pz9t2iFfyIgLP7NEs%2BoD10i2eh%2FFWKwPEucJ3Ls9XV2fqfkFwsiA6%2FHQZvdzLs5MnbFjZ2c4uk2atSkUUnRGZ8xk5T39h6D52Ep26zw%3D"); + System.out.println(URLEncoder.encode(message)); + // 私钥:请保存好 + String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKKhGMjcjNkjxu0tTPUc2euB1ckVDIKbEftzLPL4qkg+WuD7sElQO2MeHdwkkYZ4zruuhpwyjIuaKkzwx5Zea1X2ufwMTT6ehArhTNuacB1zVSb4/n5p0ICAnrTjTy5CktdPCT2iMgr83AOQVBOigF8BNULf1tM2a/NG+LKJlbAnAgMBAAECgYEAlNWuYxVFaewOQD23MpQG9DvMtcynuFfG60MLHgppfNhkP4bYXSAqWZnUZgapkFG7kZQ16XlxmsmqcOPjJUCgJX85wjr3dUJ1P7hIVeV0eEFOM8EIRiznKL+ihtiQqhd3aHXIlx2S70RJFugt8tkB6kF+mpprSauLImLnD8imE4ECQQDySc+5Njsz+qC8z5/okPJlP5qVM19sqZ2PH+d8Lk/RuBp6N+8WGnVUhCC40pLtFiZTndGAUkV76+dH8uscb8xHAkEAq9U2iiSTqmm3zP1+Ju5DCx681mdklxWRR7d5UGOsJue6/asrrNIaTOy/lt9mRGOOvJhSWxRMexRRJmDGV+1NIQJATxbbENlsD/ajG58m0tLl3Tka69M+NglUHlFKzhWMBqhzNCwoBm4SmMkcqVhLj8roLelZZur0NZR3Bdx89OZlpwJAf6Pv0Yn+DrZdC+65SN3v+1Cn4XQIKpqgwm8ttGN1u6ijJE+EL+oaE05BuybTZrW1j65ubq2TalHbPfDhJOtnQQJANAEPhhCsQdAiJfMUn+Xx2CEifjOpjN4ZJNdqHEkyf42SnVJiwAhTWrhV0dhzytZXdJt6gN0X8P/ycrPbJGh6Rw=="; + String messageDes = decrypt(message, privateKey); + System.out.println("还原后的明文为:" + messageDes); + + //tokenid + } + + /** + * RSA私钥解密 + * + * @param str 加密字符串 + * @param privateKey 私钥 + * @return 明文 + * @throws Exception 解密过程中的异常信息 + */ + public static String decrypt(String str, String privateKey) throws Exception { + //64位解码加密后的字符串 + byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8")); + //base64编码的私钥 + byte[] decoded = Base64.decodeBase64(privateKey); + RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded)); + //RSA解密 + Cipher cipher = Cipher.getInstance("RSA"); + cipher.init(Cipher.DECRYPT_MODE, priKey); + return new String(cipher.doFinal(inputByte)); + } +} diff --git a/src/main/java/com/fr/plugin/rcsso/utils/ResponseUtils.java b/src/main/java/com/fr/plugin/rcsso/utils/ResponseUtils.java new file mode 100644 index 0000000..38d534b --- /dev/null +++ b/src/main/java/com/fr/plugin/rcsso/utils/ResponseUtils.java @@ -0,0 +1,94 @@ +package com.fr.plugin.rcsso.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/rcsso/utils/Utils.java b/src/main/java/com/fr/plugin/rcsso/utils/Utils.java new file mode 100644 index 0000000..a1004d4 --- /dev/null +++ b/src/main/java/com/fr/plugin/rcsso/utils/Utils.java @@ -0,0 +1,198 @@ +package com.fr.plugin.rcsso.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"); + FRUtils.FRLogInfo("userAgent:"+userAgent); + 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; + } +}