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.

152 lines
4.6 KiB

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