1. 添加依赖

  1. <dependency>
  2. <groupId>io.jsonwebtoken</groupId>
  3. <artifactId>jjwt-api</artifactId>
  4. <version>0.11.2</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>io.jsonwebtoken</groupId>
  8. <artifactId>jjwt-impl</artifactId>
  9. <version>0.11.2</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>io.jsonwebtoken</groupId>
  13. <artifactId>jjwt-jackson</artifactId>
  14. <version>0.11.2</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>com.fasterxml.jackson.core</groupId>
  18. <artifactId>jackson-core</artifactId>
  19. <version>2.7.3</version>
  20. </dependency>
  21. <dependency>
  22. <groupId>com.fasterxml.jackson.core</groupId>
  23. <artifactId>jackson-databind</artifactId>
  24. <version>2.7.3</version>
  25. </dependency>
  26. <dependency>
  27. <groupId>com.fasterxml.jackson.core</groupId>
  28. <artifactId>jackson-annotations</artifactId>
  29. <version>2.7.3</version>
  30. </dependency>

2. 工具类

  1. import io.jsonwebtoken.*;
  2. import javax.crypto.SecretKey;
  3. import javax.crypto.spec.SecretKeySpec;
  4. import java.util.Date;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. /**
  8. * @author polaris <450733605@qq.com>
  9. * Description 数据质量管理Token工具类
  10. * Date 2020-12-28 13:16
  11. * Version 1.0.0
  12. */
  13. public class JwtUtil {
  14. // 默认过期时间
  15. private static final long EXPIRE_TIME = 1 * 60 * 1000;
  16. // 密钥(服务重启后会随机生成,不推荐使用)
  17. private static final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
  18. //private static final Key key = Keys.secretKeyFor(signatureAlgorithm);
  19. // token秘钥(长度需要达到加密算法要求,过短会抛异常)
  20. // 以下错误是由于更改了${TOKEN_SECRET}
  21. // JWT signature does not match locally computed signature. JWT validity cannot be asserted and should not be trusted.
  22. private static final String TOKEN_SECRET = "1AsdadSAS123daXXsdafsadpolarisdf34234fdfsdfdsfdsafsd";
  23. /**
  24. * 生成token
  25. *
  26. * @param param 自定义参数或者覆盖jwt参数,默认有效期30分钟
  27. * @return
  28. */
  29. public static String token(Map<String, Object> param) {
  30. String token = Jwts.builder()
  31. .setClaims(param)
  32. .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME))
  33. .signWith(generalKey(), signatureAlgorithm)
  34. .compact();
  35. return token;
  36. }
  37. /**
  38. * 生成token(指定有效期)
  39. *
  40. * @param param
  41. * @param expireTimeMillis 有效期(毫秒数)
  42. * @return
  43. */
  44. public static String token(Map<String, Object> param, Long expireTimeMillis) {
  45. SecretKey secretKey = generalKey();
  46. long nowMillis = System.currentTimeMillis();
  47. JwtBuilder builder = Jwts.builder()
  48. .setClaims(param)
  49. .signWith(secretKey, signatureAlgorithm);
  50. if (expireTimeMillis >= 0) {
  51. long expMillis = nowMillis + expireTimeMillis;
  52. Date exp = new Date(expMillis);
  53. builder.setExpiration(exp);
  54. }
  55. return builder.compact();
  56. }
  57. /**
  58. * 解析Token
  59. *
  60. * @param token
  61. * @return
  62. */
  63. public static Map<String, Object> parserToken(String token) {
  64. Map<String, Object> map = new HashMap<>();
  65. Jws<Claims> claimsJws;
  66. try {
  67. claimsJws = Jwts.parserBuilder().setSigningKey(generalKey()).build().parseClaimsJws(token);
  68. claimsJws.getBody().forEach((k, v) -> map.put(k, v));
  69. } catch (ExpiredJwtException ee) {
  70. System.err.println(ee.getMessage());
  71. return null;
  72. } catch (Exception e) {
  73. System.err.println(">>>>>>>>>>>>>>>>>" + e.getMessage());
  74. return null;
  75. }
  76. return map;
  77. }
  78. /**
  79. * 验证Token有效性
  80. * @param token
  81. * @return
  82. */
  83. public static boolean verify(String token) {
  84. try {
  85. Jwts.parserBuilder().setSigningKey(generalKey()).build().parseClaimsJws(token);
  86. return true;
  87. }catch (ExpiredJwtException ee){
  88. System.err.println(ee.getMessage());
  89. return false;
  90. }catch (Exception e) {
  91. e.printStackTrace();
  92. return false;
  93. }
  94. }
  95. /**
  96. * 由字符串生成加密key
  97. *
  98. * @return
  99. */
  100. public static SecretKey generalKey() {
  101. byte[] encodedKey = TOKEN_SECRET.getBytes();// Base64.decodeBase64(TOKEN_SECRET);
  102. SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "HmacSHA256");
  103. return key;
  104. }
  105. public static void main(String[] args) {
  106. Map<String, Object> param = new HashMap<>();
  107. param.put("username", "sha san");
  108. param.put("password", "123");
  109. String token = token(param);
  110. System.out.println(String.format("token:{%s}",token));
  111. System.out.println("-----------------------------------------------------");
  112. token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwYXNzd29yZCI6IjEyMyIsImV4cCI6MTYwOTE1MjU2OCwidXNlcm5hbWUiOiJzaGEgc2FuIn0._eOF0ftDWuL0G2kBBXWn2sft5UwNhqxAaYHJmfvT0KA";
  113. if(verify(token)){
  114. System.out.println("验证成功!");
  115. }else{
  116. System.out.println("验证失败!");
  117. }
  118. Map<String, Object> resMap =parserToken(token);
  119. System.out.println("=====================================================");
  120. System.out.println(resMap);
  121. }
  122. }