JwtUtils.kt 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package cn.gygxzc.envir.config.jwt
  2. import io.jsonwebtoken.Jwts
  3. import io.jsonwebtoken.SignatureAlgorithm
  4. import java.security.Key
  5. import java.util.*
  6. /**
  7. * Created by niantuo on 2018/9/21.
  8. * 签发jwt方法,
  9. */
  10. object JwtUtils {
  11. /**
  12. * 暂时如此,后期可以考虑ip,域名这些加强验证
  13. */
  14. fun sign(payload: JwtPayload, jwtConfig: JwtConfig): String {
  15. val calendar = Calendar.getInstance(Locale.CANADA)
  16. calendar.add(Calendar.HOUR_OF_DAY, jwtConfig.expired.toHours().toInt())
  17. return Jwts.builder()
  18. .setId(payload.id)
  19. .setSubject(payload.username)
  20. .setExpiration(calendar.time)
  21. .signWith(jwtConfig.key,SignatureAlgorithm.HS256)
  22. .compact()
  23. }
  24. /**
  25. * 解析出放进去的结果
  26. */
  27. @Throws(Exception::class)
  28. fun parseJwt(key: Key, jwtToken: String): JwtPayload {
  29. val parser = Jwts.parser()
  30. .setSigningKey(key)
  31. .parseClaimsJws(jwtToken)
  32. val id = parser.body.id
  33. val username = parser.body.subject
  34. return JwtPayload(id, username)
  35. }
  36. }