TokenUtil.java 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package com.huimv.common.utils;
  2. import cn.hutool.core.date.DateUtil;
  3. import com.auth0.jwt.JWT;
  4. import com.auth0.jwt.JWTVerifier;
  5. import com.auth0.jwt.algorithms.Algorithm;
  6. import com.auth0.jwt.interfaces.DecodedJWT;
  7. import java.time.format.DateTimeFormatter;
  8. import java.util.Date;
  9. /**
  10. * @Project : huimv.shiwan
  11. * @Package : com.example.demo.util
  12. * @Description : TODO
  13. * @Author : yuxuexuan
  14. * @Create : 2021/2/26 0026 9:06
  15. **/
  16. public class TokenUtil {
  17. private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000; //有效时长
  18. private static final String TOKEN_SECRET = "ben"; // 秘钥
  19. /**
  20. * 签名 生成
  21. *
  22. * @parm userName
  23. */
  24. public static String sign(String userName) {
  25. String token = null;
  26. try {
  27. Date expiresAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
  28. token = JWT.create()
  29. .withIssuer("auth0")
  30. .withClaim("userName", userName)
  31. .withExpiresAt(expiresAt)
  32. //使用HMAC256算法加密
  33. .sign(Algorithm.HMAC256(TOKEN_SECRET));
  34. } catch (Exception e) {
  35. e.printStackTrace();
  36. }
  37. return token;
  38. }
  39. /**
  40. * 签名验证
  41. *
  42. * @param token
  43. */
  44. public static boolean verify(String token) {
  45. try {
  46. JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET))
  47. .withIssuer("auth0").build();
  48. DecodedJWT jwt = verifier.verify(token);
  49. System.out.println("TOKEN过期时间:" + DateUtil.format(jwt.getExpiresAt(), "yyyy-MM-dd HH:mm:ss"));
  50. return true;
  51. } catch (Exception e) {
  52. return false;
  53. }
  54. }
  55. }