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.

147 lines
4.0 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 claims.ExpiresAt - time.Now().Unix()<claims.BufferTime {
  51. claims.ExpiresAt = time.Now().Unix() + 60*60*24*7
  52. newToken,_ := j.CreateToken(*claims)
  53. newClaims,_ := j.ParseToken(newToken)
  54. c.Header("new-token",newToken)
  55. c.Header("new-expires-at",strconv.FormatInt(newClaims.ExpiresAt,10))
  56. if global.GVA_CONFIG.System.UseMultipoint {
  57. err,RedisJwtToken := service.GetRedisJWT(newClaims.Username)
  58. if err!=nil {
  59. global.GVA_LOG.Error("get redis jwt failed", zap.Any("err", err))
  60. }else{
  61. service.JsonInBlacklist(model.JwtBlacklist{Jwt: RedisJwtToken})
  62. //当之前的取成功时才进行拉黑操作
  63. }
  64. // 无论如何都要记录当前的活跃状态
  65. _ = service.SetRedisJWT(newToken,newClaims.Username)
  66. }
  67. }
  68. c.Set("claims", claims)
  69. c.Next()
  70. }
  71. }
  72. type JWT struct {
  73. SigningKey []byte
  74. }
  75. var (
  76. TokenExpired = errors.New("Token is expired")
  77. TokenNotValidYet = errors.New("Token not active yet")
  78. TokenMalformed = errors.New("That's not even a token")
  79. TokenInvalid = errors.New("Couldn't handle this token:")
  80. )
  81. func NewJWT() *JWT {
  82. return &JWT{
  83. []byte(global.GVA_CONFIG.JWT.SigningKey),
  84. }
  85. }
  86. // 创建一个token
  87. func (j *JWT) CreateToken(claims request.CustomClaims) (string, error) {
  88. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  89. return token.SignedString(j.SigningKey)
  90. }
  91. // 解析 token
  92. func (j *JWT) ParseToken(tokenString string) (*request.CustomClaims, error) {
  93. token, err := jwt.ParseWithClaims(tokenString, &request.CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {
  94. return j.SigningKey, nil
  95. })
  96. if err != nil {
  97. if ve, ok := err.(*jwt.ValidationError); ok {
  98. if ve.Errors&jwt.ValidationErrorMalformed != 0 {
  99. return nil, TokenMalformed
  100. } else if ve.Errors&jwt.ValidationErrorExpired != 0 {
  101. // Token is expired
  102. return nil, TokenExpired
  103. } else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
  104. return nil, TokenNotValidYet
  105. } else {
  106. return nil, TokenInvalid
  107. }
  108. }
  109. }
  110. if token != nil {
  111. if claims, ok := token.Claims.(*request.CustomClaims); ok && token.Valid {
  112. return claims, nil
  113. }
  114. return nil, TokenInvalid
  115. } else {
  116. return nil, TokenInvalid
  117. }
  118. }
  119. // 更新token
  120. //func (j *JWT) RefreshToken(tokenString string) (string, error) {
  121. // jwt.TimeFunc = func() time.Time {
  122. // return time.Unix(0, 0)
  123. // }
  124. // token, err := jwt.ParseWithClaims(tokenString, &request.CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
  125. // return j.SigningKey, nil
  126. // })
  127. // if err != nil {
  128. // return "", err
  129. // }
  130. // if claims, ok := token.Claims.(*request.CustomClaims); ok && token.Valid {
  131. // jwt.TimeFunc = time.Now
  132. // claims.StandardClaims.ExpiresAt = time.Now().Unix() + 60*60*24*7
  133. // return j.CreateToken(*claims)
  134. // }
  135. // return "", TokenInvalid
  136. //}