JwtUtils.java 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package com.yaozhitech.spring5.utils;
  2. import java.io.UnsupportedEncodingException;
  3. import java.util.Calendar;
  4. import java.util.Date;
  5. import com.auth0.jwt.JWT;
  6. import com.auth0.jwt.JWTVerifier;
  7. import com.auth0.jwt.algorithms.Algorithm;
  8. import com.auth0.jwt.exceptions.JWTDecodeException;
  9. import com.auth0.jwt.interfaces.DecodedJWT;
  10. import lombok.extern.slf4j.Slf4j;
  11. @Slf4j
  12. public class JwtUtils {
  13. /**
  14. * 获得token中的信息无需secret解密也能获得
  15. * @return token中包含的签发时间
  16. */
  17. public static Date getIssuedAt(String token) {
  18. try {
  19. DecodedJWT jwt = JWT.decode(token);
  20. return jwt.getIssuedAt();
  21. } catch (JWTDecodeException e) {
  22. return null;
  23. }
  24. }
  25. /**
  26. * 获得token中的信息无需secret解密也能获得
  27. * @return token中包含的用户名
  28. */
  29. public static String getUsername(String token) {
  30. try {
  31. DecodedJWT jwt = JWT.decode(token);
  32. return jwt.getClaim("username").asString();
  33. } catch (JWTDecodeException e) {
  34. return null;
  35. }
  36. }
  37. public static String verifyTokenAndGet(String token, String secret) {
  38. DecodedJWT jwt = null;
  39. try {
  40. JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
  41. jwt = verifier.verify(token);
  42. } catch (Exception e) {
  43. log.error(e.getMessage(), e);
  44. return null;
  45. }
  46. return jwt.getClaim("username").asString();
  47. }
  48. /**
  49. * 生成签名,expireTime后过期
  50. * @param username 用户名
  51. * @param time 过期时间s
  52. * @return 加密的token
  53. */
  54. public static String sign(String username, String salt, long time) {
  55. try {
  56. Date date = new Date(System.currentTimeMillis()+time*1000);
  57. Algorithm algorithm = Algorithm.HMAC256(salt);
  58. // 附带username信息
  59. return JWT.create()
  60. .withClaim("username", username)
  61. .withExpiresAt(date)
  62. .withIssuedAt(new Date())
  63. .sign(algorithm);
  64. } catch (UnsupportedEncodingException e) {
  65. return null;
  66. }
  67. }
  68. /**
  69. * token是否过期
  70. * @return true:过期
  71. */
  72. public static boolean isTokenExpired(String token) {
  73. Date now = Calendar.getInstance().getTime();
  74. DecodedJWT jwt = JWT.decode(token);
  75. return jwt.getExpiresAt().before(now);
  76. }
  77. // /**
  78. // * 生成随机盐,长度32位
  79. // * @return
  80. // */
  81. // public static String generateSalt(){
  82. // SecureRandomNumberGenerator secureRandom = new SecureRandomNumberGenerator();
  83. // String hex = secureRandom.nextBytes(16).toHex();
  84. // return hex;
  85. // }
  86. }