Jwt工具类

在开发中,我们可能会用到JWT去做编码与解码问题,下面就是简单的jwt相关编解码工具类。

  1. 引入jwt依赖
    compile group: 'io.jsonwebtoken', name: 'jjwt', version: '0.9.1'
    
  2. demo工具
    @Slf4j
    public class JwtUtil {
    
        public static String encode(String key, Map param, String salt){
            if(salt!=null){
                key+=salt;
            }
            JwtBuilder jwtBuilder = Jwts.builder().signWith(SignatureAlgorithm.HS256,key);
    
            jwtBuilder = jwtBuilder.setClaims(param);
    
            String token = jwtBuilder.compact();
            return token;
    
        }
    
    
        public  static Map decode(String token , String key, String salt){
            Claims claims=null;
            if (salt!=null){
                key+=salt;
            }
            try {
                claims= Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
            } catch ( JwtException e) {
                log.error("JWT解码出现异常,e:", e);
                return null;
            }
            return  claims;
        }
    
        public static void main(String[] args) {
            String key = "token_key";
            String ip="192.168.1.1";
            Map map = new HashMap();
            map.put("userId","1001");
            map.put("nickName","tony");
            String token = JwtUtil.encode(key, map, ip);
            Map decode = JwtUtil.decode(token, key, "192.168.1.1");
            System.out.println(token);
            System.out.println(decode);
    
        }
    }
    

你可能感兴趣的:(工具类,学习,jwt,java)