JwtUtils.java 2.3 KB

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