浏览代码

Merge remote-tracking branch 'origin/dev/one' into dev/one

wangyu 6 年之前
父节点
当前提交
c83b31f7b0

文件差异内容过多而无法显示
+ 17 - 2
common/src/main/java/com/diagbot/util/JwtUtil.java


+ 1 - 0
config-server/src/main/resources/shared/user-service-dev.yml

@@ -70,6 +70,7 @@ spring:
       idc: 1 # 不可见ID索引
       sms: 2 # Redis短信索引
       img: 3 # Redis图片验证码索引
+      token: 4 # Token索引
     host: 192.168.2.236  #Redis服务器地址
     port: 6379 # Redis服务器连接端口
     password: lantone # Redis服务器连接密码(默认为空)

+ 1 - 0
config-server/src/main/resources/shared/user-service-local.yml

@@ -70,6 +70,7 @@ spring:
       idc: 11 # 不可见ID索引
       sms: 12 # Redis短信索引
       img: 13 # Redis图片验证码索引
+      token: 14 # Token索引
     host: 192.168.2.236  #Redis服务器地址
     port: 6379 # Redis服务器连接端口
     password: lantone # Redis服务器连接密码(默认为空)

+ 1 - 0
config-server/src/main/resources/shared/user-service-test.yml

@@ -70,6 +70,7 @@ spring:
       idc: 1 # 不可见ID索引
       sms: 2 # Redis短信索引
       img: 3 # Redis图片验证码索引
+      token: 4 # Token索引
     host: 192.168.2.241  #Redis服务器地址
     port: 6379 # Redis服务器连接端口
     password: lantone # Redis服务器连接密码(默认为空)

+ 2 - 0
gateway-service/src/main/java/com/diagbot/client/UserServiceClient.java

@@ -19,6 +19,8 @@ public interface UserServiceClient {
     @PostMapping("/user/login")
     RespDTO<User> login(@RequestParam("username") String username, @RequestParam("password") String password);
 
+    @PostMapping("/user/verifyToken")
+    RespDTO<Boolean> verifyToken(@RequestParam("token") String token);
 }
 
 

+ 6 - 0
gateway-service/src/main/java/com/diagbot/client/hystrix/UserServiceHystrix.java

@@ -19,4 +19,10 @@ public class UserServiceHystrix implements UserServiceClient {
         log.error("【hystrix】调用{}异常", "login");
         return null;
     }
+
+    @Override
+    public RespDTO<Boolean> verifyToken(String token) {
+        log.error("【hystrix】调用{}异常", "verifyToken");
+        return null;
+    }
 }

+ 10 - 0
gateway-service/src/main/java/com/diagbot/filter/GlobalGatewayFilter.java

@@ -5,6 +5,7 @@ import com.diagbot.client.UserServiceClient;
 import com.diagbot.dto.RespDTO;
 import com.diagbot.entity.ServiceToken;
 import com.diagbot.util.GsonUtil;
+import com.diagbot.util.StringUtil;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
@@ -70,6 +71,15 @@ public class GlobalGatewayFilter implements GlobalFilter {
         log.info("APIURL:{}", requestUri);
         log.info("SERVICENAME:{}", serviceName);
 
+        //验证token有效性
+        String token = request.getHeaders().getFirst("Authorization");
+        if(StringUtil.isNotEmpty(token)) {
+            RespDTO<Boolean> res = userServiceClient.verifyToken(token);
+            if (res == null || !RespDTO.TRUE_CODE.equals(res.code)) {
+                return getVoidMono(serverWebExchange, res);
+            }
+        }
+
         //        if(!IS_GENERATE) {
         //            RespDTO<List<ServiceFilter>> filter = diagbotmanServiceClient.getAll();
         //            if (filter != null){

+ 13 - 0
user-service/src/main/java/com/diagbot/config/RedisConfigurer.java

@@ -34,6 +34,8 @@ public class RedisConfigurer extends CachingConfigurerSupport {
     private String databaseSms;
     @Value("${spring.redis.database.img}")
     private String databaseImg;
+    @Value("${spring.redis.database.token}")
+    private String databaseToken;
     @Value("${spring.redis.host}")
     private String host;
     @Value("${spring.redis.password}")
@@ -171,6 +173,17 @@ public class RedisConfigurer extends CachingConfigurerSupport {
         return getRedisTemplate(factory, Integer.valueOf(databaseImg));
     }
 
+    /**
+     * Token使用的redis
+     *
+     * @param factory
+     * @return
+     */
+    @Bean(name = "redisTemplateForToken")
+    public RedisTemplate<String, Object> redisTemplateForToken(JedisConnectionFactory factory) {
+        return getRedisTemplate(factory, Integer.valueOf(databaseToken));
+    }
+
     private RedisTemplate<String, Object> getRedisTemplate(JedisConnectionFactory factory, Integer database) {
         JedisConnectionFactory factory2 = new JedisConnectionFactory();
         BeanUtil.copyProperties(factory, factory2);

+ 1 - 0
user-service/src/main/java/com/diagbot/config/ResourceServerConfigurer.java

@@ -44,6 +44,7 @@ public class ResourceServerConfigurer extends ResourceServerConfigurerAdapter {
                 .antMatchers("/user/verifyExistUsername").permitAll()
                 .antMatchers("/userAuthentication/getAuthInfoCount").permitAll()
                 .antMatchers("/user/getUserAllInfo").permitAll()
+                .antMatchers("/user/verifyToken").permitAll()
                 .antMatchers("/**").authenticated();
         //        .antMatchers("/**").permitAll();
     }

+ 1 - 0
user-service/src/main/java/com/diagbot/config/security/UrlAccessDecisionManager.java

@@ -88,6 +88,7 @@ public class UrlAccessDecisionManager implements AccessDecisionManager {
                 || matchers("/user/verifyExistUsername", request)
                 || matchers("/userAuthentication/getAuthInfoCount", request)
                 || matchers("/user/getUserAllInfo", request)
+                || matchers("/user/verifyToken", request)
                 || matchers("/", request)) {
             return true;
         }

+ 13 - 0
user-service/src/main/java/com/diagbot/facade/TokenFacade.java

@@ -0,0 +1,13 @@
+package com.diagbot.facade;
+
+import com.diagbot.service.impl.TokenServiceImpl;
+import org.springframework.stereotype.Component;
+
+/**
+ * @Description: token实现
+ * @author: gaodm
+ * @time: 2018/10/29 14:24
+ */
+@Component
+public class TokenFacade extends TokenServiceImpl {
+}

+ 24 - 0
user-service/src/main/java/com/diagbot/service/TokenService.java

@@ -0,0 +1,24 @@
+package com.diagbot.service;
+
+/**
+ * @Description: Token验证类
+ * @author: gaodm
+ * @time: 2018/10/29 13:35
+ */
+public interface TokenService {
+
+    /**
+     * 创建token
+     * @param token 用户token
+     * @return
+     */
+    Boolean createToken(String token);
+
+    /**
+     * 验证token是否有效
+     * @param token 待验证的token
+     * @return 返回token
+     */
+    Boolean verifyToken(String token);
+
+}

+ 112 - 0
user-service/src/main/java/com/diagbot/service/impl/TokenServiceImpl.java

@@ -0,0 +1,112 @@
+package com.diagbot.service.impl;
+
+import com.auth0.jwt.interfaces.Claim;
+import com.auth0.jwt.interfaces.DecodedJWT;
+import com.diagbot.service.TokenService;
+import com.diagbot.util.DateUtil;
+import com.diagbot.util.JwtUtil;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.dao.DataAccessException;
+import org.springframework.data.redis.connection.RedisConnection;
+import org.springframework.data.redis.core.RedisCallback;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.stereotype.Service;
+
+import java.util.Date;
+import java.util.Map;
+
+/**
+ * @Description: Token验证类 实现
+ * @author: gaodm
+ * @time: 2018/10/29 13:34
+ */
+@Slf4j
+@Service
+public class TokenServiceImpl implements TokenService {
+
+    @Autowired
+    @Qualifier("redisTemplateForToken")
+    RedisTemplate redisForToken;
+
+    private byte[] serializeKey(Object o) {
+        return redisForToken.getKeySerializer().serialize(o);
+    }
+
+    private byte[] serializeValue(Object o) {
+        return redisForToken.getValueSerializer().serialize(o);
+    }
+
+    private Object deserializeValue(byte[] b) {
+        return redisForToken.getValueSerializer().deserialize(b);
+    }
+
+    private byte[] getUserTokenKey(String userId) {
+        String userTokensFormat = "user_tokens_%s";
+        return serializeKey(String.format(userTokensFormat, userId));
+    }
+
+    /**
+     * 创建token
+     *
+     * @param token 用户token
+     * @return
+     */
+    @Override
+    public Boolean createToken(String token) {
+        DecodedJWT jwt = JwtUtil.decodedJWT(token);
+        Map<String, Claim> claims = jwt.getClaims();
+        String userId = claims.get("user_id").asInt().toString();
+        Date expDate = claims.get("exp").asDate();
+        final byte[] redis_key = getUserTokenKey(userId);
+        redisForToken.execute(new RedisCallback<Object>() {
+            @Override
+            public Object doInRedis(RedisConnection connection) throws DataAccessException {
+                //获取旧的
+                byte[] bytes = connection.get(redis_key);
+                //删除旧的
+                if (bytes != null) {
+                    connection.del(bytes);
+                }
+                //设置新的
+                connection.setEx(
+                        redis_key,
+                        (expDate.getTime() - DateUtil.now().getTime()) / 1000,
+                        serializeValue(token)
+                );
+                return true;
+            }
+        });
+        return true;
+    }
+
+    /**
+     * 验证token是否有效
+     *
+     * @param token 待验证的token
+     * @return 返回token
+     */
+    @Override
+    public Boolean verifyToken(String token) {
+        String userId = JwtUtil.getUserId(token);
+        //从redis中取出
+        final byte[] redis_key = getUserTokenKey(userId);
+        String tokenStore = (String) redisForToken.execute(new RedisCallback<String>() {
+            @Override
+            public String doInRedis(RedisConnection connection) throws DataAccessException {
+                byte[] bytes = connection.get(redis_key);
+                if (bytes == null) {
+                    return null;
+                }
+                return (String) deserializeValue(bytes);
+            }
+        });
+
+        if (null != tokenStore && tokenStore.equals(token)) {
+            return true;
+        } else {
+            return false;
+        }
+    }
+}

+ 16 - 0
user-service/src/main/java/com/diagbot/web/UserController.java

@@ -11,6 +11,7 @@ import com.diagbot.dto.UserOrgDTO;
 import com.diagbot.entity.Permission;
 import com.diagbot.entity.User;
 import com.diagbot.facade.PermissionFacade;
+import com.diagbot.facade.TokenFacade;
 import com.diagbot.facade.UserFacade;
 import com.diagbot.vo.AppkeySecretVO;
 import com.diagbot.vo.BaseIdVO;
@@ -52,6 +53,8 @@ public class UserController {
     @Autowired
     private UserFacade userFacade;
     @Autowired
+    private TokenFacade tokenFacade;
+    @Autowired
     private PermissionFacade permissionFacade;
 
 
@@ -72,6 +75,19 @@ public class UserController {
     }
 
 
+
+    @ApiOperation(value = "验证token有效性[by:zhoutg]",
+            notes = "token:token信息,必填<br>")
+    @PostMapping("/verifyToken")
+    @SysLogger("verifyToken")
+    @ApiIgnore
+    public RespDTO<Boolean> verifyToken(@RequestBody String token) {
+        Boolean data = tokenFacade.verifyToken(token);
+        return RespDTO.onSuc(data);
+    }
+
+
+
     @ApiOperation(value = "校验用户(手机号)已注册[by:zhoutg]",
             notes = "username:用户名(手机号),必填<br>")
     @PostMapping("/verifyExistUsername")