zj
2025-01-06 0e7b38c2b3af72ea2a7f8a2fcbaad4d78e2c1977
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
package com.gear.common.utils.jwt;
 
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
 
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
 
public class JWTTokenUtils {
    public static String SECRET = "HUIYUAN-CORAL-PLATFORM";
 
    public static String createToken(String userId,String phone,String client) {
        String token = null;
        try {
            //签发日期
            Date iatDate = new Date();
 
            //过期时间
            Calendar nowTime = Calendar.getInstance();
            nowTime.add(Calendar.HOUR, 12);
            Date expirseDate = nowTime.getTime();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("alg", "HS256");
            map.put("typ", "JWT");
            token = JWT.create()
                    .withIssuer(userId)//user实体
                    .withHeader(map)//jwt-header
                    .withClaim("userId", userId)
                    .withClaim("phone", phone)
                    .withClaim("client",client)
                    .withIssuedAt(iatDate)//设置签发时间
                    .withKeyId(userId)
                    .withExpiresAt(expirseDate)//设置过期时间
                    .sign(Algorithm.HMAC256(SECRET));//加密
        } catch (IOException e) {
            return token;
        }
        return token;
    }
    /**
     * 解密
     *
     * @param token
     * @return
     */
    public static String verifyToken(String token) throws  Exception{
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            DecodedJWT decodedJWT = jwtVerifier.verify(token);
            String userid = decodedJWT.getIssuer();
            return userid;
    }
 
 
 
}