JwtUtils.java 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package com.care.util;
  2. import cn.hutool.json.JSONUtil;
  3. import com.care.common.vo.UserLogindConvertVO;
  4. import io.jsonwebtoken.Claims;
  5. import io.jsonwebtoken.Jwts;
  6. import io.jsonwebtoken.SignatureAlgorithm;
  7. import org.apache.commons.codec.binary.Base64;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. import org.springframework.context.annotation.PropertySource;
  11. import org.springframework.core.env.Environment;
  12. import org.springframework.stereotype.Component;
  13. import javax.annotation.Resource;
  14. import javax.crypto.SecretKey;
  15. import javax.crypto.spec.SecretKeySpec;
  16. import java.security.Key;
  17. import java.util.Date;
  18. /**
  19. * Created by y on 2017/11/16.
  20. * @author y
  21. */
  22. @Component
  23. @PropertySource(value = "classpath:common.properties", ignoreResourceNotFound = true)
  24. public class JwtUtils {
  25. private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);
  26. @Resource
  27. private Environment env;
  28. /**
  29. * 由字符串生成加密key
  30. * @return
  31. */
  32. public SecretKey generalKey() {
  33. String stringKey = env.getProperty("auth.jwt.id") + env.getProperty("auth.jwt.secret");
  34. byte[] encodedKey = Base64.decodeBase64(stringKey);
  35. SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
  36. return key;
  37. }
  38. public String generalToken(UserLogindConvertVO userLogindConvertDTO) {
  39. String compactJws = null;
  40. try {
  41. long nowMillis = System.currentTimeMillis();
  42. Date now = new Date(nowMillis);
  43. Key key = generalKey();
  44. compactJws = Jwts.builder()
  45. .setSubject(JSONUtil.toJsonStr(userLogindConvertDTO))
  46. .setIssuedAt(now)
  47. .signWith(SignatureAlgorithm.HS512, key)
  48. .setExpiration(new Date(nowMillis + env.getProperty("auth.jwt.ttl.ms", Long.class)))
  49. .compact();
  50. } catch (Exception e) {
  51. logger.error("生成TOKEN出现异常.", e);
  52. }
  53. return compactJws;
  54. }
  55. /**
  56. * 解密jwt
  57. * @param jwt
  58. * @return
  59. * @throws Exception
  60. */
  61. public Claims tokenParse(String jwt) {
  62. SecretKey key = generalKey();
  63. Claims claims = null;
  64. try {
  65. claims = Jwts.parser()
  66. .setSigningKey(key)
  67. .parseClaimsJws(jwt).getBody();
  68. } catch (io.jsonwebtoken.ExpiredJwtException e) {
  69. System.out.println("当前TOKEN已过期, 请重新登录.");
  70. } catch (Exception e) {
  71. System.out.println("校验TOKEN出现异常, 请重新登录.");
  72. }
  73. return claims;
  74. }
  75. }