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.

153 lines
4.2 KiB

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