SysTokenServiceImpl.java 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. package com.diagbot.service.impl;
  2. import com.auth0.jwt.interfaces.Claim;
  3. import com.auth0.jwt.interfaces.DecodedJWT;
  4. import com.diagbot.entity.JwtStore;
  5. import com.diagbot.service.SysTokenService;
  6. import com.diagbot.util.DateUtil;
  7. import com.diagbot.util.JwtUtil;
  8. import lombok.extern.slf4j.Slf4j;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.beans.factory.annotation.Qualifier;
  11. import org.springframework.dao.DataAccessException;
  12. import org.springframework.data.redis.connection.RedisConnection;
  13. import org.springframework.data.redis.core.RedisCallback;
  14. import org.springframework.data.redis.core.RedisTemplate;
  15. import org.springframework.stereotype.Service;
  16. import java.util.Date;
  17. import java.util.List;
  18. import java.util.Map;
  19. /**
  20. * @Description: Token验证类 实现
  21. * @author: gaodm
  22. * @time: 2018/10/29 13:34
  23. */
  24. @Slf4j
  25. @Service
  26. public class SysTokenServiceImpl implements SysTokenService {
  27. @Autowired
  28. @Qualifier("redisTemplateForToken")
  29. RedisTemplate redisForToken;
  30. private byte[] serializeKey(Object o) {
  31. return redisForToken.getKeySerializer().serialize(o);
  32. }
  33. private byte[] serializeValue(Object o) {
  34. return redisForToken.getValueSerializer().serialize(o);
  35. }
  36. private Object deserializeValue(byte[] b) {
  37. return redisForToken.getValueSerializer().deserialize(b);
  38. }
  39. private byte[] getUserTokenKey(String userId) {
  40. String userTokensFormat = "user_tokens_%s";
  41. return serializeKey(String.format(userTokensFormat, userId));
  42. }
  43. /**
  44. * 创建token
  45. *
  46. * @param token 用户token
  47. * @return
  48. */
  49. @Override
  50. public Boolean createToken(JwtStore token) {
  51. DecodedJWT jwt = JwtUtil.decodedJWT(token.getRefreshToken());
  52. Map<String, Claim> claims = jwt.getClaims();
  53. String userId = claims.get("user_id").asInt().toString();
  54. Date expDate = claims.get("exp").asDate();
  55. final byte[] redis_key = getUserTokenKey(userId);
  56. redisForToken.execute(new RedisCallback<Object>() {
  57. @Override
  58. public Object doInRedis(RedisConnection connection) throws DataAccessException {
  59. //获取旧的
  60. byte[] bytes = connection.get(redis_key);
  61. //删除旧的
  62. if (bytes != null) {
  63. connection.del(bytes);
  64. }
  65. //设置新的
  66. connection.setEx(
  67. redis_key,
  68. (expDate.getTime() - DateUtil.now().getTime()) / 1000,
  69. serializeValue(token)
  70. );
  71. return true;
  72. }
  73. });
  74. return true;
  75. }
  76. /**
  77. * 验证token是否有效
  78. *
  79. * @param token 待验证的token
  80. * @param type 1:accessToken,2:refreshToken
  81. * @return
  82. */
  83. @Override
  84. public Boolean verifyToken(String token, Integer type) {
  85. Boolean res = false;
  86. if (null == token) {
  87. return false;
  88. }
  89. String userId = JwtUtil.getUserId(token);
  90. //从redis中取出
  91. final byte[] redis_key = getUserTokenKey(userId);
  92. JwtStore tokenStore = (JwtStore) redisForToken.execute(new RedisCallback<JwtStore>() {
  93. @Override
  94. public JwtStore doInRedis(RedisConnection connection) throws DataAccessException {
  95. byte[] bytes = connection.get(redis_key);
  96. if (bytes == null) {
  97. return null;
  98. }
  99. return (JwtStore) deserializeValue(bytes);
  100. }
  101. });
  102. if (null != tokenStore) {
  103. if (type == 1) {
  104. if (null != tokenStore.getAccessToken() && tokenStore.getAccessToken().equals(token)) {
  105. res = true;
  106. }
  107. }
  108. if (type == 2) {
  109. if (null != tokenStore.getRefreshToken() && tokenStore.getRefreshToken().equals(token)) {
  110. res = true;
  111. }
  112. }
  113. }
  114. return res;
  115. }
  116. /**
  117. * 验证token是否有效
  118. *
  119. * @param token 待验证的token
  120. * @param type 1:accessToken,2:refreshToken
  121. * @return -1:token无效(与服务器token不一致,异地登录),1:token有效,0:其他
  122. */
  123. @Override
  124. public int newVerifyToken(String token, Integer type) {
  125. Integer res = 0;
  126. if (null == token) {
  127. return 0;
  128. }
  129. String userId = JwtUtil.getUserId(token);
  130. //从redis中取出
  131. final byte[] redis_key = getUserTokenKey(userId);
  132. JwtStore tokenStore = (JwtStore) redisForToken.execute(new RedisCallback<JwtStore>() {
  133. @Override
  134. public JwtStore doInRedis(RedisConnection connection) throws DataAccessException {
  135. byte[] bytes = connection.get(redis_key);
  136. if (bytes == null) {
  137. return null;
  138. }
  139. return (JwtStore) deserializeValue(bytes);
  140. }
  141. });
  142. if (null != tokenStore) {
  143. if (type == 1) {
  144. if (null != tokenStore.getAccessToken()) {
  145. if (tokenStore.getAccessToken().equals(token)) {
  146. res = 1;
  147. } else {
  148. res = -1;
  149. }
  150. }
  151. }
  152. if (type == 2) {
  153. if (null != tokenStore.getRefreshToken()) {
  154. if (tokenStore.getRefreshToken().equals(token)) {
  155. res = 1;
  156. } else {
  157. res = -1;
  158. }
  159. }
  160. }
  161. } else {
  162. res = -2; //redis取不到token原因是因为用户权限修改被清空掉了,如果是到时钱被清空会先提示用户登录超时
  163. }
  164. return res;
  165. }
  166. /**
  167. * 删除用户token
  168. *
  169. * @param userId 用户ID
  170. * @return 删除是否成功
  171. */
  172. @Override
  173. public Boolean deleteToken(String userId) {
  174. final byte[] redis_key = getUserTokenKey(userId);
  175. Long l = (Long) redisForToken.execute(new RedisCallback<Long>() {
  176. @Override
  177. public Long doInRedis(RedisConnection connection) throws DataAccessException {
  178. return connection.del(redis_key);
  179. }
  180. });
  181. return l > 0;
  182. }
  183. /**
  184. * 批量删除用户token
  185. *
  186. * @param userIds 用户列表
  187. * @return 删除是否成功
  188. */
  189. @Override
  190. public Boolean deleteBatchToken(List<Long> userIds) {
  191. Long l = (Long) redisForToken.execute(new RedisCallback<Long>() {
  192. @Override
  193. public Long doInRedis(RedisConnection connection) throws DataAccessException {
  194. connection.openPipeline();
  195. Long cnt = 0L;
  196. for (Long userId : userIds) {
  197. byte[] redis_key = getUserTokenKey(userId.toString());
  198. connection.del(redis_key);
  199. cnt++;
  200. }
  201. connection.closePipeline();
  202. return cnt;
  203. }
  204. });
  205. return l > 0;
  206. }
  207. /**
  208. * 获取用户jwt
  209. *
  210. * @param userId 用户ID
  211. * @return jwt信息
  212. */
  213. @Override
  214. public JwtStore getToken(String userId) {
  215. JwtStore tokenStore = null;
  216. //从redis中取出
  217. final byte[] redis_key = getUserTokenKey(userId);
  218. tokenStore = (JwtStore) redisForToken.execute(new RedisCallback<JwtStore>() {
  219. @Override
  220. public JwtStore doInRedis(RedisConnection connection) throws DataAccessException {
  221. byte[] bytes = connection.get(redis_key);
  222. if (bytes == null) {
  223. return null;
  224. }
  225. return (JwtStore) deserializeValue(bytes);
  226. }
  227. });
  228. return tokenStore;
  229. }
  230. }