WXF 3 роки тому
батько
коміт
59637a0513

+ 3 - 1
simulation-oauth-client/src/main/java/com/css/simulation/oauth/client/controller/SignController.java

@@ -14,6 +14,7 @@ import com.css.simulation.oauth.client.configuration.oauth.OauthParameter;
 import com.css.simulation.oauth.client.mapper.LogLoginMapper;
 import com.css.simulation.oauth.client.mapper.UserMapper;
 import com.css.simulation.oauth.client.util.EncodeUtil;
+import com.css.simulation.oauth.client.util.IpUtil;
 import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import lombok.SneakyThrows;
@@ -236,7 +237,8 @@ public class SignController {
         LogLoginPO po = new LogLoginPO();
         po.setId(StringUtil.getRandomUUID());
         po.setCreateTime(TimeUtil.getNowForMysql());
-        po.setIp(request.getRemoteAddr());
+        String remoteAddress = IpUtil.getRemoteAddress(request);
+        po.setIp(remoteAddress);
         //登录逻辑判断
         if (userVO == null ) {
             return new ResponseBodyVO<>(ResponseBodyVO.Response.CLIENT_FAILURE, "用户名或密码错误!");

+ 54 - 0
simulation-oauth-client/src/main/java/com/css/simulation/oauth/client/util/IpUtil.java

@@ -0,0 +1,54 @@
+package com.css.simulation.oauth.client.util;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class IpUtil {
+
+    //IP地址获取
+    public static String getRemoteAddress(HttpServletRequest headers) {
+        String ip = headers.getHeader("x-forwarded-for");
+        if(ip != null && ip.length() != 0){
+            if(ip.indexOf(",") != -1){
+                ip = ip.split(",")[0];
+            }
+        }
+        if(ip == null || ip.length() == 0){
+            ip = headers.getHeader("Proxy-Client-IP");
+        }
+        if(ip == null || ip.length() == 0){
+            ip = headers.getHeader("WL-Proxy-Client-IP");
+        }
+        if(ip == null || ip.length() == 0){
+            ip = headers.getHeader("HTTP_CLIENT_IP");
+        }
+        if(ip == null || ip.length() == 0){
+            ip = headers.getHeader("HTTP_X_FORWARDED_FOR");
+        }
+        if(ip == null || ip.length() == 0){
+            ip = headers.getHeader("X-Real-IP");
+        }
+        if(ip == null || ip.length() == 0){
+            ip = headers.getRemoteAddr();
+        }
+        if(isIpv4(ip)){
+            return ip;
+        }else{
+            return "Illegal IP address";
+        }
+
+    }
+
+    //IP地址验证,防止非法地址
+    public static boolean isIpv4(String ipAddress) {
+        String ip = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
+                +"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
+                +"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
+                +"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
+
+        Pattern pattern = Pattern.compile(ip);
+        Matcher matcher = pattern.matcher(ipAddress);
+        return matcher.matches();
+    }
+}