Fixiaobai
2023-10-08 0bc9c6f3152c35f0e1236238f7310a12032395a7
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
package com.yuanchu.tms.utils;
 
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;
 
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
 
@Component
public class Jwt {
    private final String SECRET = "value";
 
    public String createJwt(String name,int id, int time) {
        HashMap<String, Object> headers = new HashMap<>();
        Calendar expires = Calendar.getInstance();
        expires.add(Calendar.MINUTE, time);
        String jwtToken = JWT.create()
                // 第一部分Header
                .withHeader(headers)
                // 第二部分Payload
                .withClaim("name", name)
                .withClaim("id", id)
                .withExpiresAt(expires.getTime())
                // 第三部分Signature
                .sign(Algorithm.HMAC256(SECRET));
        return jwtToken;
    }
 
    public Map<String, String> readJWT(String token) {
        Map<String, String> map = new HashMap<>();
        map.put("state", "0");
        map.put("info", "正常");
        map.put("data", null);
        // 创建一个验证的对象
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT verify;
        try {
            verify = jwtVerifier.verify(token);
            Map<String, String> maps = new HashMap<>();
            maps.put("id",verify.getClaim("id").toString());
            maps.put("name",verify.getClaim("name").toString());
            map.put("data", JackSonUtil.marshal(maps));
        } catch (Exception e) {
            String info = ("" + e).contains("expired") ? "已过期" : "无效签名";
            String state = ("" + e).contains("expired") ? "1" : "2";
            map.put("state", state);
            map.put("info", info);
        }
        return map;
    }
 
}