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.

143 lines
4.2 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. "github.com/dgrijalva/jwt-go"
  10. "github.com/gin-gonic/gin"
  11. "go.uber.org/zap"
  12. "strconv"
  13. "time"
  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.CreateToken(*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. // 解析 token
  88. func (j *JWT) ParseToken(tokenString string) (*request.CustomClaims, error) {
  89. token, err := jwt.ParseWithClaims(tokenString, &request.CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {
  90. return j.SigningKey, nil
  91. })
  92. if err != nil {
  93. if ve, ok := err.(*jwt.ValidationError); ok {
  94. if ve.Errors&jwt.ValidationErrorMalformed != 0 {
  95. return nil, TokenMalformed
  96. } else if ve.Errors&jwt.ValidationErrorExpired != 0 {
  97. // Token is expired
  98. return nil, TokenExpired
  99. } else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
  100. return nil, TokenNotValidYet
  101. } else {
  102. return nil, TokenInvalid
  103. }
  104. }
  105. }
  106. if token != nil {
  107. if claims, ok := token.Claims.(*request.CustomClaims); ok && token.Valid {
  108. return claims, nil
  109. }
  110. return nil, TokenInvalid
  111. } else {
  112. return nil, TokenInvalid
  113. }
  114. }
  115. // 更新token
  116. //func (j *JWT) RefreshToken(tokenString string) (string, error) {
  117. // jwt.TimeFunc = func() time.Time {
  118. // return time.Unix(0, 0)
  119. // }
  120. // token, err := jwt.ParseWithClaims(tokenString, &request.CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
  121. // return j.SigningKey, nil
  122. // })
  123. // if err != nil {
  124. // return "", err
  125. // }
  126. // if claims, ok := token.Claims.(*request.CustomClaims); ok && token.Valid {
  127. // jwt.TimeFunc = time.Now
  128. // claims.StandardClaims.ExpiresAt = time.Now().Unix() + 60*60*24*7
  129. // return j.CreateToken(*claims)
  130. // }
  131. // return "", TokenInvalid
  132. //}