TokenUtil.java 1.7 KB

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