JwtUtils.java 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /**
  2. * YIDATA集成平台
  3. *
  4. * http://yiidata.com
  5. *
  6. *
  7. */
  8. package com.yiidata.amc.hub.config;
  9. import io.jsonwebtoken.Claims;
  10. import io.jsonwebtoken.Jwts;
  11. import io.jsonwebtoken.SignatureAlgorithm;
  12. import org.slf4j.Logger;
  13. import org.slf4j.LoggerFactory;
  14. import org.springframework.boot.context.properties.ConfigurationProperties;
  15. import org.springframework.stereotype.Component;
  16. import java.util.Date;
  17. /**
  18. * jwt工具类
  19. *
  20. * @author Mark sunlightcs@gmail.com
  21. */
  22. @ConfigurationProperties(prefix = "amc.jwt")
  23. @Component
  24. public class JwtUtils {
  25. private Logger logger = LoggerFactory.getLogger(getClass());
  26. private String secret;
  27. private long expire;
  28. private String header;
  29. /**
  30. * 生成jwt token
  31. */
  32. public String generateToken(long userId) {
  33. Date nowDate = new Date();
  34. //过期时间
  35. Date expireDate = new Date(nowDate.getTime() + expire * 1000);
  36. return Jwts.builder()
  37. .setHeaderParam("typ", "JWT")
  38. .setSubject(userId+"")
  39. .setIssuedAt(nowDate)
  40. .setExpiration(expireDate)
  41. .signWith(SignatureAlgorithm.HS512, secret)
  42. .compact();
  43. }
  44. public Claims getClaimByToken(String token) {
  45. try {
  46. return Jwts.parser()
  47. .setSigningKey(secret)
  48. .parseClaimsJws(token)
  49. .getBody();
  50. }catch (Exception e){
  51. logger.debug("validate is token error ", e);
  52. return null;
  53. }
  54. }
  55. /**
  56. * token是否过期
  57. * @return true:过期
  58. */
  59. public boolean isTokenExpired(Date expiration) {
  60. return expiration.before(new Date());
  61. }
  62. public String getSecret() {
  63. return secret;
  64. }
  65. public void setSecret(String secret) {
  66. this.secret = secret;
  67. }
  68. public long getExpire() {
  69. return expire;
  70. }
  71. public void setExpire(long expire) {
  72. this.expire = expire;
  73. }
  74. public String getHeader() {
  75. return header;
  76. }
  77. public void setHeader(String header) {
  78. this.header = header;
  79. }
  80. }