shikeying
2024-01-11 3b67e947e36133e2a40eb2737b15ea375e157ea0
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
package com.walker.web.token;
 
import com.walker.infrastructure.utils.StringUtils;
import com.walker.web.TokenException;
import com.walker.web.TokenGenerator;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
 
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
 
public class JwtTokenGenerator implements TokenGenerator {
 
    private static final long ONE_MINUTE_MILLS = 1 * 60 * 1000;
 
    @Override
    public String createToken(String userId, long expiredMinutes, String magicKey) {
//        if(StringUtils.isEmpty(claims)){
//            throw new IllegalArgumentException("createToken error: claims is required!");
//        }
//
//        JwtBuilder builder = Jwts.builder().setIssuer(NAME_OWNER)
//                .setIssuedAt(new Date())
//                .setSubject(claims)
//                .signWith(SignatureAlgorithm.HS512, magicKey);
//
//        long expiredTime = 0;
//        if(expiredMinutes > 0){
//            expiredTime = System.currentTimeMillis() + expiredMinutes * ONE_MINUTE_MILLS;
//            builder.setExpiration(new Date(expiredTime));
//            logger.debug("token 过期时间:" + expiredTime);
//        }
//        return builder.compact();
        return this.createToken(null, userId, expiredMinutes, magicKey);
    }
 
    @Override
    public String createToken(String userKey, String userId, long expiredMinutes, String magicKey){
        if(StringUtils.isEmpty(userId)){
            throw new IllegalArgumentException("createToken error: userId is required!");
        }
 
        JwtBuilder builder = Jwts.builder().setIssuer(NAME_OWNER)
                .setIssuedAt(new Date());
//                .setSubject(userId);
        // 如果存在,设置用户缓存唯一标识(UUID),2022-11-01
        Map<String, Object> claims = new HashMap<>(2);
        if(StringUtils.isNotEmpty(userKey)){
            claims.put(NAME_lOGIN_USER_KEY, userKey);
            claims.put(NAME_USER_ID_KEY, userId);
        } else {
            claims.put(NAME_USER_ID_KEY, userId);
        }
        builder.addClaims(claims);
        builder.signWith(SignatureAlgorithm.HS512, magicKey);
 
        long expiredTime = 0;
        if(expiredMinutes > 0){
            expiredTime = System.currentTimeMillis() + expiredMinutes * ONE_MINUTE_MILLS;
            builder.setExpiration(new Date(expiredTime));
            logger.debug("token 过期时间:" + expiredTime);
        }
        return builder.compact();
    }
 
    @Override
    public String validateToken(String token, String secretKey) throws TokenException {
        try{
            Claims c = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();
            if(c == null){
                throw new TokenException("token claims is null!");
            }
            StringBuilder sb = new StringBuilder(c.get(NAME_USER_ID_KEY).toString());
            if(c.get(NAME_lOGIN_USER_KEY) != null){
                sb.append(StringUtils.DEFAULT_SPLIT_SEPARATOR);
                sb.append(c.get(NAME_lOGIN_USER_KEY).toString());
            }
            return sb.toString();
//            return c.getSubject();
        } catch (Exception ex){
            if(ex instanceof SignatureException){
                throw new TokenException("token签名解析错误", ex);
            } else if(ex instanceof ExpiredJwtException){
                throw new TokenException("token过期", ex, true);
            } else {
                throw new TokenException(ex.getMessage(), ex);
            }
        }
    }
 
//    public String getDataFromToken(String token, String secretKey){
//        try{
//            Claims c = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();
//            if(c == null){
////                throw new TokenException("token claims is null!");
//                System.out.println("解析token业务数据时,返回null");
//                return null;
//            }
//        } catch (Exception ex){
//        }
//    }
 
    @Override
    public String acquireSecretKey() {
        return null;
    }
 
//    private String getData(Claims c){
//        StringBuilder sb = new StringBuilder(c.get(NAME_USER_ID_KEY).toString());
//        if(c.get(NAME_lOGIN_USER_KEY) != null){
//            sb.append(StringUtils.DEFAULT_SPLIT_SEPARATOR);
//            sb.append(c.get(NAME_lOGIN_USER_KEY).toString());
//        }
//        return sb.toString();
//    }
}