diff --git a/README.md b/README.md index 2215c68..4c65bd9 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,6 @@ # open-JSD-8798 -JSD-8798 移动端单点+IP白名单 \ No newline at end of file +JSD-8798 移动端单点+IP白名单 开源任务材料\ +免责说明:该源码为第三方爱好者提供,不保证源码和方案的可靠性,也不提供任何形式的源码教学指导和协助!\ +仅作为开发者学习参考使用!禁止用于任何商业用途!\ +为保护开发者隐私,开发者信息已隐去!若原开发者希望公开自己的信息,可联系hugh处理。 \ No newline at end of file diff --git a/plugin.xml b/plugin.xml new file mode 100644 index 0000000..0f67b07 --- /dev/null +++ b/plugin.xml @@ -0,0 +1,22 @@ + + com.fr.plugin.ipsso + + yes + 1.0.2 + 10.0 + 2018-07-31 + author + + + com.fr.plugin.ipsso + + + + + + + + + + \ No newline at end of file diff --git a/src/main/java/com/fr/plugin/ipsso/config/InitializeMonitor.java b/src/main/java/com/fr/plugin/ipsso/config/InitializeMonitor.java new file mode 100644 index 0000000..d6ab44d --- /dev/null +++ b/src/main/java/com/fr/plugin/ipsso/config/InitializeMonitor.java @@ -0,0 +1,21 @@ +package com.fr.plugin.ipsso.config; + +import com.fr.plugin.context.PluginContext; +import com.fr.plugin.observer.inner.AbstractPluginLifecycleMonitor; + +/** + * @author fr.open + * @version 10.0 + * Created by richie 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/ipsso/config/PluginSimpleConfig.java b/src/main/java/com/fr/plugin/ipsso/config/PluginSimpleConfig.java new file mode 100644 index 0000000..73940ca --- /dev/null +++ b/src/main/java/com/fr/plugin/ipsso/config/PluginSimpleConfig.java @@ -0,0 +1,57 @@ +package com.fr.plugin.ipsso.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.ipsso.config", text = "单点登录配置", source = Original.PLUGIN) + public static PluginSimpleConfig getInstance() { + if (config == null) { + config = ConfigContext.getConfigInstance(PluginSimpleConfig.class); + } + return config; + } + + @Identifier(value = "appId", name = "appId", description = "appId", status = Status.SHOW) + private Conf appId = Holders.simple("1"); + + @Identifier(value = "secret", name = "secret", description = "secret", status = Status.SHOW) + private Conf secret = Holders.simple("1"); + + public String getAppId() { + return appId.get(); + } + + public void setAppId(String url) { + this.appId.set(url); + } + + public String getSecret() { + return secret.get(); + } + + public void setSecret(String url) { + this.secret.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/ipsso/filter/SSOFilter.java b/src/main/java/com/fr/plugin/ipsso/filter/SSOFilter.java new file mode 100644 index 0000000..6308b67 --- /dev/null +++ b/src/main/java/com/fr/plugin/ipsso/filter/SSOFilter.java @@ -0,0 +1,81 @@ +package com.fr.plugin.ipsso.filter; + +import com.fr.base.ServerConfig; +import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider; +import com.fr.decision.webservice.login.LogInOutResultInfo; +import com.fr.decision.webservice.utils.DecisionServiceConstants; +import com.fr.decision.webservice.v10.login.event.LogInOutEvent; +import com.fr.event.EventDispatcher; +import com.fr.log.FineLoggerFactory; +import com.fr.plugin.ipsso.utils.FRUtils; +import com.fr.plugin.ipsso.utils.Utils; +import com.fr.record.analyzer.EnableMetrics; +import com.fr.stable.StringUtils; + +import javax.servlet.FilterChain; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +@EnableMetrics +public class SSOFilter extends AbstractGlobalRequestFilterProvider { + @Override + public String filterName() { + return "ipssoFilter"; + } + + @Override + public String[] urlPatterns() { + return new String[]{"/*"}; + } + + @Override + public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain ){ + String token = req.getParameter("token"); + + + if(Utils.isNotNullStr(token)){ + writeToken2Cookie(res,token,-1); + } + HttpSession session = req.getSession(true); + + req.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME,token); + + session.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME, token); + + release(req,res,chain); + } + + private 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); + } + + } + + + //放行拦截器 + 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/ipsso/handler/ExtendAttrHandlerProvider.java b/src/main/java/com/fr/plugin/ipsso/handler/ExtendAttrHandlerProvider.java new file mode 100644 index 0000000..fd7bc83 --- /dev/null +++ b/src/main/java/com/fr/plugin/ipsso/handler/ExtendAttrHandlerProvider.java @@ -0,0 +1,13 @@ +package com.fr.plugin.ipsso.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 GetToken() + }; + } +} diff --git a/src/main/java/com/fr/plugin/ipsso/handler/GetToken.java b/src/main/java/com/fr/plugin/ipsso/handler/GetToken.java new file mode 100644 index 0000000..afe70f0 --- /dev/null +++ b/src/main/java/com/fr/plugin/ipsso/handler/GetToken.java @@ -0,0 +1,61 @@ +package com.fr.plugin.ipsso.handler; + +import com.fr.decision.fun.impl.BaseHttpHandler; +import com.fr.decision.webservice.v10.login.LoginService; +import com.fr.plugin.ipsso.config.PluginSimpleConfig; +import com.fr.plugin.ipsso.utils.IPWhiteUtils; +import com.fr.plugin.ipsso.utils.ResponseUtils; +import com.fr.plugin.transform.FunctionRecorder; +import com.fr.third.springframework.web.bind.annotation.RequestMethod; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@FunctionRecorder +public class GetToken extends BaseHttpHandler { + + + public GetToken() { + } + + @Override + public RequestMethod getMethod() { + return RequestMethod.GET; + } + + @Override + public String getPath() { + return "/getToken"; + } + + @Override + public boolean isPublic() { + return true; + } + + @Override + public void handle(HttpServletRequest req, HttpServletResponse res) throws Exception { + String token = ""; + + //获取请求参数 + String clientId = req.getParameter("clientId"); + String secret =req.getParameter("secret"); + String username = req.getParameter("username"); + + PluginSimpleConfig psc = PluginSimpleConfig.getInstance(); + String configClientid = psc.getAppId(); + String configSecret = psc.getSecret(); + + if(IPWhiteUtils.inWhite(req) && clientId.equals(configClientid) && configSecret.equals(secret)){ + token = LoginService.getInstance().login(req, res, username); + } + +// token = LoginService.getInstance().login(req, res, username); + + ResponseUtils.successResponse(res,token); + } + + + + +} + diff --git a/src/main/java/com/fr/plugin/ipsso/handler/URLAliasProvide.java b/src/main/java/com/fr/plugin/ipsso/handler/URLAliasProvide.java new file mode 100644 index 0000000..1e3908f --- /dev/null +++ b/src/main/java/com/fr/plugin/ipsso/handler/URLAliasProvide.java @@ -0,0 +1,14 @@ +package com.fr.plugin.ipsso.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("/getToken","/getToken",true), + }; + } +} diff --git a/src/main/java/com/fr/plugin/ipsso/utils/FRUtils.java b/src/main/java/com/fr/plugin/ipsso/utils/FRUtils.java new file mode 100644 index 0000000..381014d --- /dev/null +++ b/src/main/java/com/fr/plugin/ipsso/utils/FRUtils.java @@ -0,0 +1,167 @@ +package com.fr.plugin.ipsso.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/ipsso/utils/IPUtils.java b/src/main/java/com/fr/plugin/ipsso/utils/IPUtils.java new file mode 100644 index 0000000..bf1a0ce --- /dev/null +++ b/src/main/java/com/fr/plugin/ipsso/utils/IPUtils.java @@ -0,0 +1,341 @@ +package com.fr.plugin.ipsso.utils; + +import com.fr.data.NetworkHelper; +import com.fr.decision.mobile.terminal.TerminalHandler; +import com.fr.decision.webservice.v10.login.LoginService; +import com.fr.stable.web.Device; + +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class IPUtils { + + + /** + * 私有IP: + * A类 10.0.0.0-10.255.255.255 + * B类 172.16.0.0-172.31.255.255 + * C类 192.168.0.0-192.168.255.255 + * + * 127这个网段是环回地址 + * localhost + */ + static List ipFilterRegexList = new ArrayList<>(); + + static { + Set ipFilter = new HashSet(); + ipFilter.add("^10\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])" + + "\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])" + "\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])$"); + // B类地址范围: 172.16.0.0---172.31.255.255 + ipFilter.add("^172\\.(1[6789]|2[0-9]|3[01])\\" + ".(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])\\" + + ".(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])$"); + // C类地址范围: 192.168.0.0---192.168.255.255 + ipFilter.add("^192\\.168\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])\\" + + ".(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])$"); + ipFilter.add("127.0.0.1"); + ipFilter.add("0.0.0.0"); + ipFilter.add("localhost"); + for (String tmp : ipFilter) { + ipFilterRegexList.add(Pattern.compile(tmp)); + } + } + + + // IP的正则,这个正则不能验证第一组数字为0的情况 + private static Pattern pattern = Pattern + .compile("([1-9]\\d?|1\\d{2}|2[01]\\d|22[0-3])\\." + + "(1\\d{1,2}|2[0-4]\\d|25[0-5]|\\d{1,2})\\." + + "(1\\d{1,2}|2[0-4]\\d|25[0-5]|\\d{1,2})\\." + + "(1\\d{1,2}|2[0-4]\\d|25[0-5]|\\d{1,2})"); + + /** + * + * getAvaliIpList:(根据IP白名单设置获取可用的IP列表). + * + * @date 2020-11-11 下午02:50:20 + * @return + */ + + private static Set getAvaliIpList(String allowIp) { + + Set ipList = new HashSet(); + for (String allow : allowIp.replaceAll("\\s", "").split(",")) { + if (allow.indexOf("*") > -1) { + String[] ips = allow.split("\\."); + String[] from = new String[] { "0", "0", "0", "0" }; + String[] end = new String[] { "255", "255", "255", "255" }; + List tem = new ArrayList(); + for (int i = 0; i < ips.length; i++) + if (ips[i].indexOf("*") > -1) { + //todo 直接用等于,不能正确获取类似192.168.**.*这种格式的ip段 + tem = complete(ips[i]); + from[i] = null; + end[i] = null; + } else { + from[i] = ips[i]; + end[i] = ips[i]; + } + + StringBuffer fromIP = new StringBuffer(); + StringBuffer endIP = new StringBuffer(); + for (int i = 0; i < 4; i++) + if (from[i] != null) { + fromIP.append(from[i]).append("."); + endIP.append(end[i]).append("."); + } else { + fromIP.append("[*]."); + endIP.append("[*]."); + } + fromIP.deleteCharAt(fromIP.length() - 1); + endIP.deleteCharAt(endIP.length() - 1); + + for (String s : tem) { + String ip = fromIP.toString().replace("[*]", + s.split(";")[0]) + + "-" + + endIP.toString().replace("[*]", s.split(";")[1]); + if (validate(ip)) { + ipList.add(ip); + } + } + } else { + if (validate(allow)) { + ipList.add(allow); + } + } + + } + + return ipList; + } + + /** + * 对单个IP节点进行范围限定 + * + * @param arg + * @return 返回限定后的IP范围,格式为List[10;19, 100;199] + */ + private static List complete(String arg) { + List com = new ArrayList(); + if (arg.length() == 1) { + com.add("0;255"); + } else if (arg.length() == 2) { + String s1 = complete(arg, 1); + if (s1 != null) + com.add(s1); + String s2 = complete(arg, 2); + if (s2 != null) + com.add(s2); + } else { + String s1 = complete(arg, 1); + if (s1 != null) + com.add(s1); + } + return com; + } + + private static String complete(String arg, int length) { + String from = ""; + String end = ""; + if (length == 1) { + from = arg.replace("*", "0"); + end = arg.replace("*", "9"); + } else { + from = arg.replace("*", "00"); + end = arg.replace("*", "99"); + } + if (Integer.valueOf(from) > 255) + return null; + if (Integer.valueOf(end) > 255) + end = "255"; + return from + ";" + end; + } + + /** + * 在添加至白名单时进行格式校验 + * + * @param ip + * @return + */ + private static boolean validate(String ip) { + for (String s : ip.split("-")) + if (!pattern.matcher(s).matches()) { + return false; + } + return true; + } + + /** + * + * checkLoginIP:(根据IP,及可用Ip列表来判断ip是否包含在白名单之中). + * @date 2017-4-17 下午03:01:03 + * @param ip + * @param ipList + * @return + */ + private static boolean checkLoginIP(String ip, Set ipList) { + if (ipList.isEmpty() || ipList.contains(ip)) + return true; + else { + for (String allow : ipList) { + if (allow.indexOf("-") > -1) { + String[] from = allow.split("-")[0].split("\\."); + String[] end = allow.split("-")[1].split("\\."); + String[] tag = ip.split("\\."); + + // 对IP从左到右进行逐段匹配 + boolean check = true; + for (int i = 0; i < 4; i++) { + int s = Integer.valueOf(from[i]); + int t = Integer.valueOf(tag[i]); + int e = Integer.valueOf(end[i]); + if (!(s <= t && t <= e)) { + check = false; + break; + } + } + if (check) { + return true; + } + } + } + } + return false; + } + + /** + * + * checkLoginIP:(根据IP地址,及IP白名单设置规则判断IP是否包含在白名单). + * @date 2017-4-17 下午03:01:37 + * @param ip + * @param ipWhiteConfig + * @return + */ + public static boolean checkLoginIP(String ip,String ipWhiteConfig){ + Set ipList = getAvaliIpList(ipWhiteConfig); + return checkLoginIP(ip, ipList); + } + + + + + + /** + * 获取真实IP 原逻辑 + * @param request + * @return + */ + public static String getRealIp2(HttpServletRequest request) { + // 这个一般是Nginx反向代理设置的参数 + String ip = request.getHeader("X-Real-IP"); + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("X-Forwarded-For"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("Proxy-Client-IP"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("WL-Proxy-Client-IP"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getRemoteAddr(); + } + // 处理多IP的情况(只取第一个IP) + if (ip != null && ip.contains(",")) { + String[] ipArray = ip.split(","); + ip = ipArray[0]; + } + //FineLoggerFactory.getLogger().info("[ENC]客户端IP为[{}]",ip); + return ip; + } + + + /** + * 获取真实IP 客户逻辑 + * @param request + * @return + */ + public static String getRealIp(HttpServletRequest request) { + String ip = request.getHeader("X-Forwarded-For"); + if (ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("X-Real-IP"); + } + if (ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("Proxy-Client-IP"); + } + if (ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("WL-Proxy-Client-IP"); + } + if (ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)) { + ip = request.getRemoteAddr(); + } + + // 处理多IP的情况(只取第一个IP) + if (ip != null && ip.contains(",")) { + String[] ipArray = ip.split(","); + ip = ipArray[0]; + } + + return ip; + } + + + + + /** + * 判断IP是否内网IP + * @Title: ipIsInner + * @param ip + * @return: boolean + */ + public static boolean ipIsInner(String ip) { + boolean isInnerIp = false; + for (Pattern tmp : ipFilterRegexList) { + Matcher matcher = tmp.matcher(ip); + if (matcher.find()) { + isInnerIp = true; + break; + } + } + return isInnerIp; + } + + + // token有效性检验 + public static boolean checkTokenValid(HttpServletRequest req, String token) { + + // 判断该token是否还保存在状态服务器中,也就是判断该token是否还有用 + try { + Device device = NetworkHelper.getDevice(req); + LoginService.getInstance().loginStatusValid(token, TerminalHandler.getTerminal(req, device)); + return true; + } catch (Exception e) { + } + return false; + } + + + /** + * 判断是否是内网IP "192.168.1.1," + //设置单个IP的白名单 + * "192.168.*.2," + //设置ip通配符,对一个ip段进行匹配 + * "192.168.3.17-192.168.3.38"; //设置一个IP范围 + * @param ip + * @return + */ + public static boolean isInnerIP(String ip,String ipWhite) throws IOException { + String ip4[]=ip.split("\\."); + if(ip4.length==4) { + return checkLoginIP(ip,ipWhite); + }else{ + return false; + } + } + + +} diff --git a/src/main/java/com/fr/plugin/ipsso/utils/IPWhiteUtils.java b/src/main/java/com/fr/plugin/ipsso/utils/IPWhiteUtils.java new file mode 100644 index 0000000..cf7575d --- /dev/null +++ b/src/main/java/com/fr/plugin/ipsso/utils/IPWhiteUtils.java @@ -0,0 +1,79 @@ +package com.fr.plugin.ipsso.utils; + +import com.fr.data.NetworkHelper; +import com.fr.decision.webservice.v10.config.ConfigService; +import com.fr.decision.webservice.v10.login.TokenResource; +import com.fr.io.utils.ResourceIOUtils; +import com.fr.log.FineLoggerFactory; +import com.fr.plugin.transform.FunctionRecorder; +import com.fr.stable.StringUtils; +import com.fr.third.springframework.web.util.WebUtils; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.Properties; + +@FunctionRecorder +public class IPWhiteUtils{ + + private static String ipWhite; + private static String servletName="decision"; + + + + public static boolean inWhite(HttpServletRequest req) { + try { + servletName = ConfigService.getInstance().getBasicParam().getServletPathName(); + } catch (Exception e) { + FineLoggerFactory.getLogger().error("[ENC]获取servletName失败"); + e.printStackTrace(); + } + + + Properties pro = new Properties(); + try { + pro.load(ResourceIOUtils.read("/resources/ip4enc.properties")); + FineLoggerFactory.getLogger().error("[ENC]IP白名单获取失败"); + } catch (IOException e) { + e.printStackTrace(); + } + ipWhite= pro.getProperty("ipWhite",StringUtils.EMPTY); + + String ip= IPUtils.getRealIp(req); + //内网标记 + boolean isInnerIPFlag= false; + try { + isInnerIPFlag = IPUtils.isInnerIP(ip,ipWhite); + } catch (IOException e) { + FineLoggerFactory.getLogger().error("[ENC]判断IP失败"); + } + + //移动设备标记 + boolean isMobileFlag=NetworkHelper.getDevice(req).isMobile(); + + //移动端原生登陆标记 + boolean isMobileLoginFlag=req.getRequestURI().contains(servletName+"/login") && !isInnerIPFlag; + + //微信登陆标记 + boolean isDingLoginFlag=req.getRequestURI().contains("weixin/single/login") && isMobileFlag; + + String token = TokenResource.COOKIE.getToken(req); + //是否登陆标记 + boolean isHasTokenFlag=!StringUtils.isEmpty(token) && IPUtils.checkTokenValid(req, token); + + //移动端原生登陆标记 + boolean isResourcesFlag=req.getRequestURI().contains(servletName+"/resources"); + + boolean isHasDingCookie=WebUtils.getCookie(req, "LOGIN_TYPE") != null; + + FineLoggerFactory.getLogger().debug("[ENC]内网[{}]|移动设备[{}]|移动原生登陆[{}]|微信登陆[{}]|是否登陆[{}]|请求[{}]",isInnerIPFlag,isMobileFlag,isMobileLoginFlag,isDingLoginFlag,isHasTokenFlag,req.getRequestURI()); + + if(isInnerIPFlag || isResourcesFlag || isHasDingCookie){ + return true; + } + else if(isDingLoginFlag){ + return true; + } else{ + return false; + } + } +} diff --git a/src/main/java/com/fr/plugin/ipsso/utils/ResponseUtils.java b/src/main/java/com/fr/plugin/ipsso/utils/ResponseUtils.java new file mode 100644 index 0000000..f57af94 --- /dev/null +++ b/src/main/java/com/fr/plugin/ipsso/utils/ResponseUtils.java @@ -0,0 +1,94 @@ +package com.fr.plugin.ipsso.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/ipsso/utils/Utils.java b/src/main/java/com/fr/plugin/ipsso/utils/Utils.java new file mode 100644 index 0000000..a580f1f --- /dev/null +++ b/src/main/java/com/fr/plugin/ipsso/utils/Utils.java @@ -0,0 +1,197 @@ +package com.fr.plugin.ipsso.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; + } +} diff --git a/使用手册.docx b/使用手册.docx new file mode 100644 index 0000000..c196e45 Binary files /dev/null and b/使用手册.docx differ