1. 添加依赖

  1. <dependency>
  2. <groupId>com.auth0</groupId>
  3. <artifactId>java-jwt</artifactId>
  4. <version>3.8.2</version>
  5. <exclusions>
  6. <exclusion>
  7. <artifactId>commons-codec</artifactId>
  8. <groupId>commons-codec</groupId>
  9. </exclusion>
  10. </exclusions>
  11. </dependency>
  12. <dependency>
  13. <groupId>commons-codec</groupId>
  14. <artifactId>commons-codec</artifactId>
  15. <version>1.11</version>
  16. </dependency>

2. 工具类

  1. import com.auth0.jwt.JWT;
  2. import com.auth0.jwt.JWTCreator;
  3. import com.auth0.jwt.JWTVerifier;
  4. import com.auth0.jwt.algorithms.Algorithm;
  5. import com.auth0.jwt.exceptions.TokenExpiredException;
  6. import com.auth0.jwt.interfaces.Claim;
  7. import com.auth0.jwt.interfaces.DecodedJWT;
  8. import java.util.Date;
  9. import java.util.HashMap;
  10. import java.util.Map;
  11. /**
  12. * @author polaris <450733605@qq.com>
  13. * Description JWT Token工具类
  14. * Date 2020-12-28 17:53
  15. * Version 1.0.0
  16. */
  17. public class JwtUtil {
  18. // 设置过期时间
  19. private static final long EXPIRE_DATE = 1 * 60 * 1000;
  20. // token秘钥(长度需要达到加密算法要求,过短会抛异常)
  21. private static final String TOKEN_SECRET = "1AsdadSAS123daXXsdafsadpolarisdf34234fdfsdfdsfdsafsd";
  22. // 密钥(服务重启后会随机生成,不推荐使用)
  23. private static final Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
  24. /**
  25. * 生成token
  26. *
  27. * @param param 自定义参数或者覆盖jwt参数,默认有效期30分钟
  28. * @return
  29. */
  30. public static String token(Map<String, Object> param) {
  31. return token(param, null);
  32. }
  33. /**
  34. * 生成token(指定有效期)
  35. *
  36. * @param param
  37. * @param expireTimeMillis 有效期(毫秒数)
  38. * @return
  39. */
  40. public static String token(Map<String, Object> param, Long expireTimeMillis) {
  41. String token;
  42. Date expire = new Date(System.currentTimeMillis() + EXPIRE_DATE);
  43. if (expireTimeMillis != null && expireTimeMillis > 0) {
  44. expire = new Date(System.currentTimeMillis() + expireTimeMillis);
  45. }
  46. try {
  47. // 设置头部信息
  48. Map<String, Object> header = new HashMap<>();
  49. header.put("typ", "JWT");
  50. header.put("alg", "HS256");
  51. JWTCreator.Builder builder = JWT.create()
  52. .withHeader(header);
  53. if (param != null && param.size() > 0) {
  54. param.forEach((k, v) -> {
  55. builder.withClaim(k, String.valueOf(v));
  56. });
  57. }
  58. token = builder
  59. .withExpiresAt(expire)
  60. .sign(algorithm);
  61. } catch (Exception e) {
  62. e.printStackTrace();
  63. return null;
  64. }
  65. return token;
  66. }
  67. /**
  68. * 验证Token有效性
  69. * @param token
  70. * @return
  71. */
  72. public static boolean verify(String token) {
  73. try {
  74. JWTVerifier verifier = JWT.require(algorithm).build();
  75. verifier.verify(token);
  76. return true;
  77. }catch (TokenExpiredException te){
  78. System.err.println(te.getMessage());
  79. return false;
  80. }catch (Exception e) {
  81. e.printStackTrace();
  82. return false;
  83. }
  84. }
  85. /**
  86. * 解析Token
  87. *
  88. * @param token
  89. * @return
  90. */
  91. public static Map<String, Object> parserToken(String token) {
  92. Map<String, Object> map = new HashMap<>();
  93. try {
  94. DecodedJWT t=JWT.require(algorithm).build().verify(token);
  95. Map<String, Claim> claims=t.getClaims();
  96. if(claims!=null && claims.size()>0){
  97. claims.forEach((k,v) -> {
  98. if("exp".equalsIgnoreCase(k)){
  99. map.put(k, v.asDate());
  100. }else{
  101. map.put(k, v.asString());
  102. }
  103. });
  104. }
  105. }catch (TokenExpiredException te){
  106. System.err.println(te.getMessage());
  107. return null;
  108. } catch (Exception e) {
  109. e.printStackTrace();
  110. return null;
  111. }
  112. return map;
  113. }
  114. public static void main(String[] args) {
  115. Map<String, Object> param = new HashMap<>();
  116. param.put("username", "sha san");
  117. param.put("password", "123");
  118. String token = token(param);
  119. System.out.println(String.format("token:{%s}",token));
  120. System.out.println("-----------------------------------------------------");
  121. //token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwYXNzd29yZCI6IjEyMyIsImV4cCI6MTYwOTE1MjU2OCwidXNlcm5hbWUiOiJzaGEgc2FuIn0._eOF0ftDWuL0G2kBBXWn2sft5UwNhqxAaYHJmfvT0KA";
  122. if(verify(token)){
  123. System.out.println("验证成功!");
  124. }else{
  125. System.out.println("验证失败!");
  126. }
  127. Map<String, Object> resMap =parserToken(token);
  128. System.out.println("=====================================================");
  129. System.out.println(resMap);
  130. }
  131. }