XiaoRuby
2023-07-13 27e9d7d2c7db63c5f12c83e069980213398e8337
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
package com.yuanchu.limslaboratory.shiro.utils;
 
 
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
 
import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
 
@Component
public class JwtUtils {
    private static String staticSecret;
 
    @Value("${login.secret}")
    private String secret;
 
    @PostConstruct
    public void getApiToken() {
        staticSecret = this.secret;
    }
 
    public static String getSecret() {
        // lockie.zou
        return staticSecret;
    }
 
    // 过期时间 2 小时
    private static final long EXPIRE_TIME = 2 * 60 * 60 * 1000;
    //自己定制密钥
    public static final String SECRET = "J-(t]Poe9P";
 
    //请求头
    public static final String AUTH_HEADER = "X-Token";  // X-Authorization-With
 
    /**
     * 验证token是否正确
     * @param token
     * @return
     */
    public static boolean verify(String token){
        try{
            String account = getClaimFiled(token, "account");
            if (account == null){
                return false;
            }
            Algorithm algorithm = Algorithm.HMAC256(getSecret());
            JWTVerifier verifier = JWT.require(algorithm).withClaim("account",account).build();
            verifier.verify(token);
            return true;
        } catch (JWTVerificationException exception){
            return false;
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * 获得token中的自定义信息,一般是获取token的username,无需secret解密也能获得
     * @param token
     * @param filed
     * @return
     */
    public static String getClaimFiled(String token, String filed){
        try{
            if (!ObjectUtils.isEmpty(token)){
                DecodedJWT jwt = JWT.decode(token);
                return jwt.getClaim(filed).asString();
            }
            return null;
        } catch (JWTDecodeException e){
            return null;
        }
    }
 
    /**
     * 生成签名,准确地说是生成token
     * @return
     */
    public static String sign(String account){
        try{
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            //附带username,nickname信息
            return JWT.create()
                    .withClaim("account",account)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (JWTCreationException e){
            e.printStackTrace();
            return null;
        } catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
 
    /**
     * 获取token的签发时间
     * @param token
     * @return
     */
    public static Date getIssueAt(String token){
        try{
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getIssuedAt();
        } catch (JWTDecodeException e){
            e.printStackTrace();
            return null;
        }
    }
 
    /**
     * 验证token是否过期
     * @param token
     * @return
     */
    public static boolean isTokenExpired(String token){
        Date now = Calendar.getInstance().getTime();
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getExpiresAt().before(now);
    }
 
    /**
     * 刷新token的有效期
     * @param token
     * @param secret
     * @return
     */
    public static String refreshTokenExpired(String token, String secret){
        DecodedJWT jwt = JWT.decode(token); //解析token
        Map<String, Claim> claims = jwt.getClaims(); //获取token的参数信息
 
        try{
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTCreator.Builder builder = JWT.create().withExpiresAt(date);
            for(Map.Entry<String,Claim> entry : claims.entrySet()){
                builder.withClaim(entry.getKey(),entry.getValue().asString());
            }
            return builder.sign(algorithm);
        } catch (JWTCreationException e){
            e.printStackTrace();
            return null;
        }
    }
}