jwt.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. package utils
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "mtp20access/global"
  7. "mtp20access/model/common/request"
  8. "time"
  9. "github.com/golang-jwt/jwt/v4"
  10. )
  11. type JWT struct {
  12. SigningKey []byte
  13. }
  14. var (
  15. ErrTokenExpired = errors.New("token is expired")
  16. ErrTokenNotValidYet = errors.New("token not active yet")
  17. ErrTokenMalformed = errors.New("that's not even a token")
  18. ErrTokenInvalid = errors.New("couldn't handle this token ")
  19. )
  20. func NewJWT() *JWT {
  21. return &JWT{
  22. []byte(global.M2A_CONFIG.JWT.SigningKey),
  23. }
  24. }
  25. func (j *JWT) CreateClaims(baseClaims request.BaseClaims) request.CustomClaims {
  26. claims := request.CustomClaims{
  27. BaseClaims: baseClaims,
  28. BufferTime: global.M2A_CONFIG.JWT.BufferTime, // 缓冲时间1天 缓冲时间内会获得新的token刷新令牌 此时一个用户会存在两个有效令牌 但是前端只留一个 另一个会丢失
  29. RegisteredClaims: jwt.RegisteredClaims{
  30. IssuedAt: jwt.NewNumericDate(time.Now()), // 签发时间
  31. NotBefore: jwt.NewNumericDate(time.Now()), // 签名生效时间
  32. ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(global.M2A_CONFIG.JWT.ExpiresTime))), // 过期时间 7天 配置文件
  33. Issuer: global.M2A_CONFIG.JWT.Issuer, // 签名的发行者
  34. },
  35. }
  36. return claims
  37. }
  38. // 创建一个token
  39. func (j *JWT) CreateToken(claims request.CustomClaims) (string, error) {
  40. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  41. return token.SignedString(j.SigningKey)
  42. }
  43. // CreateTokenByOldToken 旧token 换新token 使用归并回源避免并发问题
  44. func (j *JWT) CreateTokenByOldToken(oldToken string, claims request.CustomClaims) (string, error) {
  45. v, err, _ := global.M2A_Concurrency_Control.Do("JWT:"+oldToken, func() (interface{}, error) {
  46. return j.CreateToken(claims)
  47. })
  48. return v.(string), err
  49. }
  50. // 解析 token
  51. func (j *JWT) ParseToken(tokenString string) (*request.CustomClaims, error) {
  52. token, err := jwt.ParseWithClaims(tokenString, &request.CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {
  53. return j.SigningKey, nil
  54. })
  55. if err != nil {
  56. if ve, ok := err.(*jwt.ValidationError); ok {
  57. if ve.Errors&jwt.ValidationErrorMalformed != 0 {
  58. return nil, ErrTokenMalformed
  59. } else if ve.Errors&jwt.ValidationErrorExpired != 0 {
  60. // Token is expired
  61. return nil, ErrTokenExpired
  62. } else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
  63. return nil, ErrTokenNotValidYet
  64. } else {
  65. return nil, ErrTokenInvalid
  66. }
  67. }
  68. }
  69. if token != nil {
  70. if claims, ok := token.Claims.(*request.CustomClaims); ok && token.Valid {
  71. return claims, nil
  72. }
  73. return nil, ErrTokenInvalid
  74. } else {
  75. return nil, ErrTokenInvalid
  76. }
  77. }
  78. //@function: JsonInBlacklist
  79. //@description: 拉黑jwt
  80. //@param: jwt string
  81. //@return: err error
  82. func (j *JWT) JsonInBlacklist(jwt string) (err error) {
  83. global.BlackCache.SetDefault(jwt, struct{}{})
  84. return
  85. }
  86. //@function: IsBlacklist
  87. //@description: 判断JWT是否在黑名单内部
  88. //@param: jwt string
  89. //@return: bool
  90. func (j *JWT) IsBlacklist(jwt string) bool {
  91. _, ok := global.BlackCache.Get(jwt)
  92. return ok
  93. }
  94. //@function: GetRedisJWT
  95. //@description: 从redis取jwt
  96. //@param: userName string
  97. //@return: redisJWT string, err error
  98. func (j *JWT) GetRedisJWT(loginID string) (redisJWT string, err error) {
  99. key := fmt.Sprintf("m2a:jwt:%s", loginID)
  100. redisJWT, err = global.M2A_REDIS.Get(context.Background(), key).Result()
  101. return redisJWT, err
  102. }
  103. //@function: SetRedisJWT
  104. //@description: jwt存入redis并设置过期时间
  105. //@param: jwt string, userName string
  106. //@return: err error
  107. func (j *JWT) SetRedisJWT(jwt string, loginID string) (err error) {
  108. key := fmt.Sprintf("m2a:jwt:%s", loginID)
  109. // 此处过期时间等于jwt过期时间
  110. timer := time.Duration(global.M2A_CONFIG.JWT.ExpiresTime) * time.Second
  111. err = global.M2A_REDIS.Set(context.Background(), key, jwt, timer).Err()
  112. return err
  113. }