You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

154 lines
4.7 KiB

3 years ago
  1. package middleware
  2. import (
  3. "errors"
  4. "gin-vue-admin/global"
  5. "gin-vue-admin/model/common/response"
  6. "gin-vue-admin/model/system"
  7. "gin-vue-admin/model/system/request"
  8. "gin-vue-admin/service"
  9. "strconv"
  10. "time"
  11. "github.com/dgrijalva/jwt-go"
  12. "github.com/gin-gonic/gin"
  13. "go.uber.org/zap"
  14. )
  15. var jwtService = service.ServiceGroupApp.SystemServiceGroup.JwtService
  16. func JWTAuth() gin.HandlerFunc {
  17. return func(c *gin.Context) {
  18. // 我们这里jwt鉴权取头部信息 x-token 登录时回返回token信息 这里前端需要把token存储到cookie或者本地localStorage中 不过需要跟后端协商过期时间 可以约定刷新令牌或者重新登录
  19. token := c.Request.Header.Get("x-token")
  20. if token == "" {
  21. response.FailWithDetailed(gin.H{"reload": true}, "未登录或非法访问", c)
  22. c.Abort()
  23. return
  24. }
  25. if jwtService.IsBlacklist(token) {
  26. response.FailWithDetailed(gin.H{"reload": true}, "您的帐户异地登陆或令牌失效", c)
  27. c.Abort()
  28. return
  29. }
  30. j := NewJWT()
  31. // parseToken 解析token包含的信息
  32. claims, err := j.ParseToken(token)
  33. if err != nil {
  34. if err == TokenExpired {
  35. response.FailWithDetailed(gin.H{"reload": true}, "授权已过期", c)
  36. c.Abort()
  37. return
  38. }
  39. response.FailWithDetailed(gin.H{"reload": true}, err.Error(), c)
  40. c.Abort()
  41. return
  42. }
  43. if err, _ = userService.FindUserByUuid(claims.UUID.String()); err != nil {
  44. _ = jwtService.JsonInBlacklist(system.JwtBlacklist{Jwt: token})
  45. response.FailWithDetailed(gin.H{"reload": true}, err.Error(), c)
  46. c.Abort()
  47. }
  48. if claims.ExpiresAt-time.Now().Unix() < claims.BufferTime {
  49. claims.ExpiresAt = time.Now().Unix() + global.GVA_CONFIG.JWT.ExpiresTime
  50. newToken, _ := j.CreateTokenByOldToken(token, *claims)
  51. newClaims, _ := j.ParseToken(newToken)
  52. c.Header("new-token", newToken)
  53. c.Header("new-expires-at", strconv.FormatInt(newClaims.ExpiresAt, 10))
  54. if global.GVA_CONFIG.System.UseMultipoint {
  55. err, RedisJwtToken := jwtService.GetRedisJWT(newClaims.Username)
  56. if err != nil {
  57. global.GVA_LOG.Error("get redis jwt failed", zap.Any("err", err))
  58. } else { // 当之前的取成功时才进行拉黑操作
  59. _ = jwtService.JsonInBlacklist(system.JwtBlacklist{Jwt: RedisJwtToken})
  60. }
  61. // 无论如何都要记录当前的活跃状态
  62. _ = jwtService.SetRedisJWT(newToken, newClaims.Username)
  63. }
  64. }
  65. c.Set("claims", claims)
  66. c.Next()
  67. }
  68. }
  69. type JWT struct {
  70. SigningKey []byte
  71. }
  72. var (
  73. TokenExpired = errors.New("Token is expired")
  74. TokenNotValidYet = errors.New("Token not active yet")
  75. TokenMalformed = errors.New("That's not even a token")
  76. TokenInvalid = errors.New("Couldn't handle this token:")
  77. )
  78. func NewJWT() *JWT {
  79. return &JWT{
  80. []byte(global.GVA_CONFIG.JWT.SigningKey),
  81. }
  82. }
  83. // 创建一个token
  84. func (j *JWT) CreateToken(claims request.CustomClaims) (string, error) {
  85. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  86. return token.SignedString(j.SigningKey)
  87. }
  88. // CreateTokenByOldToken 旧token 换新token 使用归并回源避免并发问题
  89. func (j *JWT) CreateTokenByOldToken(oldToken string, claims request.CustomClaims) (string, error) {
  90. v, err, _ := global.GVA_Concurrency_Control.Do("JWT:"+oldToken, func() (interface{}, error) {
  91. return j.CreateToken(claims)
  92. })
  93. return v.(string), err
  94. }
  95. // 解析 token
  96. func (j *JWT) ParseToken(tokenString string) (*request.CustomClaims, error) {
  97. token, err := jwt.ParseWithClaims(tokenString, &request.CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {
  98. return j.SigningKey, nil
  99. })
  100. if err != nil {
  101. if ve, ok := err.(*jwt.ValidationError); ok {
  102. if ve.Errors&jwt.ValidationErrorMalformed != 0 {
  103. return nil, TokenMalformed
  104. } else if ve.Errors&jwt.ValidationErrorExpired != 0 {
  105. // Token is expired
  106. return nil, TokenExpired
  107. } else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
  108. return nil, TokenNotValidYet
  109. } else {
  110. return nil, TokenInvalid
  111. }
  112. }
  113. }
  114. if token != nil {
  115. if claims, ok := token.Claims.(*request.CustomClaims); ok && token.Valid {
  116. return claims, nil
  117. }
  118. return nil, TokenInvalid
  119. } else {
  120. return nil, TokenInvalid
  121. }
  122. }
  123. // 更新token
  124. //func (j *JWT) RefreshToken(tokenString string) (string, error) {
  125. // jwt.TimeFunc = func() time.Time {
  126. // return time.Unix(0, 0)
  127. // }
  128. // token, err := jwt.ParseWithClaims(tokenString, &request.CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
  129. // return j.SigningKey, nil
  130. // })
  131. // if err != nil {
  132. // return "", err
  133. // }
  134. // if claims, ok := token.Claims.(*request.CustomClaims); ok && token.Valid {
  135. // jwt.TimeFunc = time.Now
  136. // claims.StandardClaims.ExpiresAt = time.Now().Unix() + 60*60*24*7
  137. // return j.CreateToken(*claims)
  138. // }
  139. // return "", TokenInvalid
  140. //}