rengb 3 лет назад
Родитель
Сommit
5176c4ef49

+ 4 - 0
common/pom.xml

@@ -84,6 +84,10 @@
             <groupId>javax.validation</groupId>
             <artifactId>validation-api</artifactId>
         </dependency>
+        <dependency>
+            <groupId>com.nimbusds</groupId>
+            <artifactId>nimbus-jose-jwt</artifactId>
+        </dependency>
         <dependency>
             <groupId>com.baomidou</groupId>
             <artifactId>mybatis-plus-extension</artifactId>

+ 95 - 0
common/src/main/java/com/lantone/common/util/HttpUtils.java

@@ -0,0 +1,95 @@
+package com.lantone.common.util;
+
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.Enumeration;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * @Description: http请求功能工具类
+ * @author: gaodm
+ * @time: 2018/8/3 17:45
+ */
+public class HttpUtils {
+
+    /**
+     * 尝试获取当前请求的HttpServletRequest实例
+     *
+     * @return
+     */
+    public static HttpServletRequest getHttpServletRequest() {
+        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
+    }
+
+    /**
+     * 获取请求头map
+     *
+     * @param request
+     * @return
+     */
+    public static Map<String, String> getHeaders(HttpServletRequest request) {
+        Map<String, String> map = new LinkedHashMap<>();
+        Enumeration<String> enumeration = request.getHeaderNames();
+        while (enumeration.hasMoreElements()) {
+            String key = enumeration.nextElement();
+            String value = request.getHeader(key);
+            map.put(key, value);
+        }
+        return map;
+    }
+
+    /**
+     * 获取请求客户端的真实ip地址
+     *
+     * @param request
+     * @return ip地址
+     */
+    public static String getIpAddress(HttpServletRequest request) {
+        // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址
+        String ip = request.getHeader("X-Forwarded-For");
+        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(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.getHeader("HTTP_CLIENT_IP");
+            }
+            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
+                ip = request.getHeader("HTTP_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.getRemoteAddr();
+            }
+        } else if (ip.length() > 15) {
+            String[] ips = ip.split(",");
+            for (int index = 0; index < ips.length; index++) {
+                String strIp = (String) ips[index];
+                if (!("unknown".equalsIgnoreCase(strIp))) {
+                    ip = strIp;
+                    break;
+                }
+            }
+        }
+        return ip;
+    }
+
+    /**
+     * 获取请求客户端的真实ip地址
+     *
+     * @return ip地址
+     */
+    public static String getIpAddress() {
+        // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址
+        return getIpAddress(getHttpServletRequest());
+    }
+
+}

+ 36 - 23
common/src/main/java/com/lantone/common/util/SysUserUtils.java

@@ -1,66 +1,79 @@
 package com.lantone.common.util;
 
+import cn.hutool.json.JSONUtil;
+import com.lantone.common.constant.AuthConstant;
+import com.lantone.common.domain.UserDto;
+import com.nimbusds.jose.JWSObject;
+
+import java.text.ParseException;
+import java.util.Map;
+
 /**
- * @Description:
- * @author:
- * @time:
+ * @Description: 用户工具类
+ * @author: rengb
+ * @time: 2021/1/5 18:27
  */
 public class SysUserUtils {
 
-    private static final String AUTHORIZATION = "authorization";
-
     /**
      * 获取当前请求的token
      *
      * @return
      */
     public static String getCurrentToken() {
-        return null;
+        Map<String, String> header = HttpUtils.getHeaders(HttpUtils.getHttpServletRequest());
+        return header.get(AuthConstant.JWT_TOKEN_HEADER);
     }
 
     /**
-     * 获取当前请求的用户名称
+     * 从token中解析出用户信息字符串
      *
+     * @param token
      * @return
+     * @throws ParseException
      */
-    public static String getCurrentPrinciple() {
-        return "0000";
+    public static String getUserStrByToken(String token) throws ParseException {
+        String realToken = token.replace(AuthConstant.JWT_TOKEN_PREFIX, "");
+        JWSObject jwsObject = JWSObject.parse(realToken);
+        return jwsObject.getPayload().toString();
     }
 
     /**
-     * 获取当前请求的用户ID
+     * 获取当前用户
      *
      * @return
      */
-    public static String getCurrentPrincipleID() {
-        return "0000";
+    public static UserDto getCurrentUser() {
+        Map<String, String> header = HttpUtils.getHeaders(HttpUtils.getHttpServletRequest());
+        UserDto userDto = JSONUtil.toBean(header.get(AuthConstant.USER_TOKEN_HEADER), UserDto.class);
+        return userDto;
     }
 
     /**
-     * 获取当前请求用户的医院ID
+     * 获取当前请求的用户名称
      *
      * @return
      */
-    public static String getCurrentHospitalID() {
-        return "0000";
+    public static String getCurrentPrinciple() {
+        return getCurrentUser().getUsername();
     }
 
     /**
-     * 判读当前token用户是否为接口所需的参数username
+     * 获取当前请求的用户ID
      *
-     * @param username
      * @return
      */
-    public static boolean isMyself(String username) {
-        return username.equals(getCurrentPrinciple());
+    public static String getCurrentPrincipleID() {
+        return getCurrentUser().getId().toString();
     }
 
     /**
-     * @param role
+     * 获取当前请求用户的医院ID
+     *
      * @return
      */
-    public static boolean hasRole(String role) {
-        return false;
+    public static String getCurrentHospitalID() {
+        return "0000";
     }
 
-}
+}

+ 2 - 5
gateway-service/src/main/java/com/lantone/authorization/AuthorizationManager.java

@@ -5,8 +5,8 @@ import cn.hutool.core.util.StrUtil;
 import cn.hutool.json.JSONUtil;
 import com.lantone.common.constant.AuthConstant;
 import com.lantone.common.domain.UserDto;
+import com.lantone.common.util.SysUserUtils;
 import com.lantone.config.IgnoreUrlsConfig;
-import com.nimbusds.jose.JWSObject;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.http.HttpMethod;
@@ -64,10 +64,7 @@ public class AuthorizationManager implements ReactiveAuthorizationManager<Author
             if (StrUtil.isEmpty(token)) {
                 return Mono.just(new AuthorizationDecision(false));
             }
-            String realToken = token.replace(AuthConstant.JWT_TOKEN_PREFIX, "");
-            JWSObject jwsObject = JWSObject.parse(realToken);
-            String userStr = jwsObject.getPayload().toString();
-            UserDto userDto = JSONUtil.toBean(userStr, UserDto.class);
+            UserDto userDto = JSONUtil.toBean(SysUserUtils.getUserStrByToken(token), UserDto.class);
             if (AuthConstant.SECURITY_CENTER_CLIENT_ID.equals(userDto.getClientId()) && !pathMatcher.match(AuthConstant.SECURITY_CENTER_URL_PATTERN, uri.getPath())) {
                 return Mono.just(new AuthorizationDecision(false));
             }

+ 5 - 11
gateway-service/src/main/java/com/lantone/filter/AuthGlobalFilter.java

@@ -2,9 +2,8 @@ package com.lantone.filter;
 
 import cn.hutool.core.util.StrUtil;
 import com.lantone.common.constant.AuthConstant;
-import com.nimbusds.jose.JWSObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import com.lantone.common.util.SysUserUtils;
+import lombok.extern.slf4j.Slf4j;
 import org.springframework.cloud.gateway.filter.GatewayFilterChain;
 import org.springframework.cloud.gateway.filter.GlobalFilter;
 import org.springframework.core.Ordered;
@@ -20,11 +19,10 @@ import java.text.ParseException;
  * @author: rengb
  * @time: 2021/1/5 18:27
  */
+@Slf4j
 @Component
 public class AuthGlobalFilter implements GlobalFilter, Ordered {
 
-    private static Logger LOGGER = LoggerFactory.getLogger(AuthGlobalFilter.class);
-
     @Override
     public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
         String token = exchange.getRequest().getHeaders().getFirst(AuthConstant.JWT_TOKEN_HEADER);
@@ -33,14 +31,10 @@ public class AuthGlobalFilter implements GlobalFilter, Ordered {
         }
         try {
             //从token中解析用户信息并设置到Header中去
-            String realToken = token.replace(AuthConstant.JWT_TOKEN_PREFIX, "");
-            JWSObject jwsObject = JWSObject.parse(realToken);
-            String userStr = jwsObject.getPayload().toString();
-            LOGGER.info("AuthGlobalFilter.filter() user:{}", userStr);
-            ServerHttpRequest request = exchange.getRequest().mutate().header(AuthConstant.USER_TOKEN_HEADER, userStr).build();
+            ServerHttpRequest request = exchange.getRequest().mutate().header(AuthConstant.USER_TOKEN_HEADER, SysUserUtils.getUserStrByToken(token)).build();
             exchange = exchange.mutate().request(request).build();
         } catch (ParseException e) {
-            e.printStackTrace();
+            log.error(e.getMessage(), e);
         }
         return chain.filter(exchange);
     }