puzhibing
2023-06-13 7860e5cb6db60aeb82c640651998f8294635df5b
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
package cn.mb.cloud.auth.util;
 
import cn.mb.cloud.auth.warpper.ParseToken;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.*;
 
import java.nio.charset.StandardCharsets;
 
public class JWTTokenUtil {
 
    private static final String SigningKey = "Bo3XdHukD8FE62ki";
 
    /**
     * 解析token
     * @param token
     * @return
     */
    public static ParseToken parseToken(String token) throws TokenException{
        //解析Token,获取Claims对象
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(SigningKey.getBytes(StandardCharsets.UTF_8))
                    .parseClaimsJws(token)
                    .getBody();
        }catch (SignatureException e){//解析失败
            throw new TokenException(10001, e.getMessage());
        }catch (MalformedJwtException e){//无效的token
            throw new TokenException(10002, "无效的票据");
        }catch (ExpiredJwtException e){
            throw new TokenException(10003, "票据已过期");
        }catch (Exception e){
            e.printStackTrace();
            throw new TokenException(10010, e.getMessage());
        }
        String string = JSON.toJSONString(claims);
        ParseToken parseToken = JSON.parseObject(string, ParseToken.class);
        return parseToken;
    }
 
 
//    public static void main(String[] ages){
//        try {
//            ParseToken s = JWTTokenUtil.parseToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ");
//            System.err.println(s.toString());
//        } catch (TokenException e) {
//            if(e.getCode() == 10001){
//                e.printStackTrace();
//            }
//            if(e.getCode() == 10002){
//                e.printStackTrace();
//            }
//        }
//    }
}