jwt.go 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package middleware
  2. import (
  3. "github.com/flipped-aurora/gin-vue-admin/server/utils"
  4. "strconv"
  5. "time"
  6. "github.com/flipped-aurora/gin-vue-admin/server/global"
  7. "github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
  8. "github.com/flipped-aurora/gin-vue-admin/server/model/system"
  9. "github.com/flipped-aurora/gin-vue-admin/server/service"
  10. "github.com/gin-gonic/gin"
  11. "go.uber.org/zap"
  12. )
  13. var jwtService = service.ServiceGroupApp.SystemServiceGroup.JwtService
  14. func JWTAuth() gin.HandlerFunc {
  15. return func(c *gin.Context) {
  16. // 我们这里jwt鉴权取头部信息 x-token 登录时回返回token信息 这里前端需要把token存储到cookie或者本地localStorage中 不过需要跟后端协商过期时间 可以约定刷新令牌或者重新登录
  17. token := c.Request.Header.Get("x-token")
  18. if token == "" {
  19. response.FailWithDetailed(gin.H{"reload": true}, "未登录或非法访问", c)
  20. c.Abort()
  21. return
  22. }
  23. if jwtService.IsBlacklist(token) {
  24. response.FailWithDetailed(gin.H{"reload": true}, "您的帐户异地登陆或令牌失效", c)
  25. c.Abort()
  26. return
  27. }
  28. j := utils.NewJWT()
  29. // parseToken 解析token包含的信息
  30. claims, err := j.ParseToken(token)
  31. if err != nil {
  32. if err == utils.TokenExpired {
  33. response.FailWithDetailed(gin.H{"reload": true}, "授权已过期", c)
  34. c.Abort()
  35. return
  36. }
  37. response.FailWithDetailed(gin.H{"reload": true}, err.Error(), c)
  38. c.Abort()
  39. return
  40. }
  41. // 用户被删除的逻辑 需要优化 此处比较消耗性能 如果需要 请自行打开
  42. //if err, _ = userService.FindUserByUuid(claims.UUID.String()); err != nil {
  43. // _ = jwtService.JsonInBlacklist(system.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 := jwtService.GetRedisJWT(newClaims.Username)
  55. if err != nil {
  56. global.GVA_LOG.Error("get redis jwt failed", zap.Any("err", err))
  57. } else { // 当之前的取成功时才进行拉黑操作
  58. _ = jwtService.JsonInBlacklist(system.JwtBlacklist{Jwt: RedisJwtToken})
  59. }
  60. // 无论如何都要记录当前的活跃状态
  61. _ = jwtService.SetRedisJWT(newToken, newClaims.Username)
  62. }
  63. }
  64. c.Set("claims", claims)
  65. c.Next()
  66. }
  67. }