Helius
2021-08-05 fdb91cc72f7cbe8c095a1ce6442c9259ff01ff06
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
package com.xzx.gc.common.utils;
 
import cn.hutool.core.codec.Base64;
import com.xzx.gc.common.constant.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
 
/**
 * @author: zhongzan
 * @create: 2019-07-16 19:01
 * @description: token工具类
 */
 
@Component
public class TokenUtil {
 
    //秘钥
//    private final static  String SECRET="0es07jwbam1k5o5q";
 
    //token有效期 30天 单位秒
//    public final static  int  TIME=30*24*3600;
 
 
    @Autowired
    private RedisUtil redisUtil;
 
 
    /**
     * 生成token
     * @param userId 用户ID
     * @return
     */
//    public String generateToken(String userId) {
//        String token = JWT.create()
//                //载体
//                .withClaim("userId", userId)
//                .withClaim("uuid",IdUtil.randomUUID())
//                //设置过期时间 不设置永久生效
//                //.withExpiresAt(new Date(System.currentTimeMillis() + TIME))
//                //jwt的唯一身份标识,主要用来作为一次性token,从而回避重放攻击
//                //.withJWTId(userId.toString())
//                //私钥加密
//                .sign(Algorithm.HMAC256(SECRET));
//        //有效时间控制由redis接管
//        redisUtil.setex(Constants.REDIS_USER_KEY+"token:"+userId,token,TIME);
//        return token;
//    }
 
    /**
     * 兼容老的生成方式
     * @param userId
     * @param token
     * @return
     */
    public void generateTokenCompatible(String userId,String token) {
        //有效时间控制由redis接管
        redisUtil.setex(Constants.REDIS_USER_KEY+"token:"+userId,token,getTimeOut());
    }
 
    public int getTimeOut(){
        if(SpringUtil.isCheck()){
            return 30*60;
        }else{
            return 30*24*3600;
        }
    }
 
 
    /**
     * 1.2版本以前的token生成方式
     * @return
     */
    public  String generateToken() throws NoSuchAlgorithmException {
        String token = (System.currentTimeMillis() + new Random().nextInt(999999999))+"";
 
            MessageDigest md = MessageDigest.getInstance("md5");
            byte md5[] = md.digest(token.getBytes());
        String encode = Base64.encode(md5);
        return encode;
    }
 
 
 
    /**验证token
     * @param token
     */
    public int verifier(String token,String userId) {
//        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
//        DecodedJWT verify=null;
//        try {
//            verify = jwtVerifier.verify(token);
//        } catch (JWTVerificationException e) {
//            // if (e.getMessage().startsWith("The Token can't be used before")) {
//                return -1;
//            // }
//            //失效交给redis处理
//            // if (e.getMessage().startsWith("The Token has expired on")) {
//            //     throw new BizException("token已过期");
//            // }
//        }
 
        //限制一个用户多终端登录同时需要验证redis的token
        String oldToken = redisUtil.get(Constants.REDIS_USER_KEY+"token:" + userId);
        if(token.equals(oldToken)){
            return 0;
        }
        return -2;
    }
 
 
//    /**
//     * 获取某个载体
//     * @param token
//     * @return
//     */
//    public String getUserId(String token){
//        String userId;
//        try {
//            userId=JWT.decode(token).getClaim("userId").asString();
//            if(userId==null){
//                throw new RestException(-2,"用户ID不能为空");
//            }
//        } catch (JWTDecodeException e) {
//            throw new RestException(-2,"token解析失败");
//        }
//        return  userId;
//    }
 
    /**
     * 删除token
     */
    public  void delete(String userId){
        redisUtil.del(Constants.REDIS_USER_KEY+"token:"+userId);
    }
 
 
    /**
     * token是否过期
     * @param userId
     * @return
     */
    public  boolean isExpire(String userId){
        if(redisUtil.exists(Constants.REDIS_USER_KEY+"token:"+userId)){
            return false;
        }
        return  true;
    }
 
 
    /**
     * 更新token有效时间
     * @param userId
     */
    public  void updateTokenExpire(String userId){
        redisUtil.expire(Constants.REDIS_USER_KEY+"token:"+userId,getTimeOut());
    }
 
 
    /**
     * 获取Token
     * @return
     */
    public  String getToken(String userId){
        String oldToken = redisUtil.get(Constants.REDIS_USER_KEY+"token:" + userId);
        if(StringUtils.isNotBlank(oldToken)){
            return oldToken;
        }
        return null;
    }
 
 
 
}