zhitong.yu
2024-10-11 4f58a93c95ff123d51adcb8fa2e521333e8ab022
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
package com.hxzk.util;
 
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
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 java.util.HashMap;
import java.util.Map;
 
@Component
public class TokenUtil {
    @Value("hfghjhrtiyerjiofmwefnwefiewhiof212424")
    private  String secretKey;
    /**
     * 加密token.
     */
    public  String getToken(String userId) {
        //这个是放到负载payLoad 里面,魔法值可以使用常量类进行封装.
        String token = JWT
                .create()
                .withClaim("userId" ,userId)
//                .withClaim("userRole", userRole)
                .withClaim("timeStamp", System.currentTimeMillis())
                .sign(Algorithm.HMAC256(secretKey));
        return token;
    }
    /**
     * 解析token.
     * {
     * "userId": "weizhong",
     * "userRole": "ROLE_ADMIN",
     * "timeStamp": "134143214"
     * }
     */
    public  String parseToken(String token) {
        HashMap<String, String> map = new HashMap<String, String>();
        DecodedJWT decodedjwt = JWT.require(Algorithm.HMAC256(secretKey))
                .build().verify(token);
        Claim userId = decodedjwt.getClaim("userId");
//        Claim userRole = decodedjwt.getClaim("userRole");
//        Claim timeStamp = decodedjwt.getClaim("timeStamp");
//        map.put("userId", userId.asString());
//        map.put("userRole", userRole.asString());
//        map.put("timeStamp", timeStamp.asLong().toString());
        return userId.asString();
    }
}