JwtTool.java 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package com.zksy.gateway.utils;
  2. import cn.hutool.core.exceptions.ValidateException;
  3. import cn.hutool.jwt.JWT;
  4. import cn.hutool.jwt.JWTValidator;
  5. import cn.hutool.jwt.signers.JWTSigner;
  6. import cn.hutool.jwt.signers.JWTSignerUtil;
  7. import com.zksy.common.exception.UnauthorizedException;
  8. import org.springframework.stereotype.Component;
  9. import java.security.KeyPair;
  10. import java.time.Duration;
  11. import java.util.Date;
  12. @Component
  13. public class JwtTool {
  14. private final JWTSigner jwtSigner;
  15. public JwtTool(KeyPair keyPair) {
  16. this.jwtSigner = JWTSignerUtil.createSigner("rs256", keyPair);
  17. }
  18. /**
  19. * 创建 access-token
  20. *
  21. * @param userId 用户信息
  22. * @return access-token
  23. */
  24. public String createToken(Long userId, Duration ttl) {
  25. // 1.生成jws
  26. return JWT.create()
  27. .setPayload("user", userId)
  28. .setExpiresAt(new Date(System.currentTimeMillis() + ttl.toMillis()))
  29. .setSigner(jwtSigner)
  30. .sign();
  31. }
  32. /**
  33. * 解析token
  34. *
  35. * @param token token
  36. * @return 解析刷新token得到的用户信息
  37. */
  38. public Long parseToken(String token) {
  39. // 1.校验token是否为空
  40. if (token == null) {
  41. throw new UnauthorizedException("未登录");
  42. }
  43. // 2.校验并解析jwt
  44. JWT jwt;
  45. try {
  46. jwt = JWT.of(token).setSigner(jwtSigner);
  47. } catch (Exception e) {
  48. throw new UnauthorizedException("无效的token", e);
  49. }
  50. // 2.校验jwt是否有效
  51. if (!jwt.verify()) {
  52. // 验证失败
  53. throw new UnauthorizedException("无效的token");
  54. }
  55. // 3.校验是否过期
  56. try {
  57. JWTValidator.of(jwt).validateDate();
  58. } catch (ValidateException e) {
  59. throw new UnauthorizedException("token已经过期");
  60. }
  61. // 4.数据格式校验
  62. Object userPayload = jwt.getPayload("user");
  63. if (userPayload == null) {
  64. // 数据为空
  65. throw new UnauthorizedException("无效的token");
  66. }
  67. // 5.数据解析
  68. try {
  69. return Long.valueOf(userPayload.toString());
  70. } catch (RuntimeException e) {
  71. // 数据格式有误
  72. throw new UnauthorizedException("无效的token");
  73. }
  74. }
  75. }