jwt.go 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package utils
  2. import (
  3. "errors"
  4. "time"
  5. jwt "github.com/golang-jwt/jwt/v4"
  6. "lcfns/global"
  7. "lcfns/model/system/request"
  8. )
  9. type JWT struct {
  10. SigningKey []byte
  11. }
  12. var (
  13. TokenExpired = errors.New("Token is expired")
  14. TokenNotValidYet = errors.New("Token not active yet")
  15. TokenMalformed = errors.New("That's not even a token")
  16. TokenInvalid = errors.New("Couldn't handle this token:")
  17. )
  18. func NewJWT() *JWT {
  19. return &JWT{
  20. []byte(global.Config.JWT.SigningKey),
  21. }
  22. }
  23. func (j *JWT) CreateClaims(baseClaims request.BaseClaims) request.CustomClaims {
  24. bf, _ := ParseDuration(global.Config.JWT.BufferTime)
  25. ep, _ := ParseDuration(global.Config.JWT.ExpiresTime)
  26. claims := request.CustomClaims{
  27. BaseClaims: baseClaims,
  28. BufferTime: int64(bf / time.Second), // 缓冲时间1天 缓冲时间内会获得新的token刷新令牌 此时一个用户会存在两个有效令牌 但是前端只留一个 另一个会丢失
  29. RegisteredClaims: jwt.RegisteredClaims{
  30. Audience: jwt.ClaimStrings{"GVA"}, // 受众
  31. NotBefore: jwt.NewNumericDate(time.Now().Add(-1000)), // 签名生效时间
  32. ExpiresAt: jwt.NewNumericDate(time.Now().Add(ep)), // 过期时间 7天 配置文件
  33. Issuer: global.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.GVA_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, TokenMalformed
  59. } else if ve.Errors&jwt.ValidationErrorExpired != 0 {
  60. // Token is expired
  61. return nil, TokenExpired
  62. } else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
  63. return nil, TokenNotValidYet
  64. } else {
  65. return nil, TokenInvalid
  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, TokenInvalid
  74. } else {
  75. return nil, TokenInvalid
  76. }
  77. }