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.

130 lines
3.3 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. "time"
  12. )
  13. func JWTAuth() gin.HandlerFunc {
  14. return func(c *gin.Context) {
  15. // 我们这里jwt鉴权取头部信息 x-token 登录时回返回token信息 这里前端需要把token存储到cookie或者本地localSstorage中 不过需要跟后端协商过期时间 可以约定刷新令牌或者重新登录
  16. token := c.Request.Header.Get("x-token")
  17. modelToken := model.JwtBlacklist{
  18. Jwt: token,
  19. }
  20. if token == "" {
  21. response.Result(response.ERROR, gin.H{
  22. "reload": true,
  23. }, "未登录或非法访问", c)
  24. c.Abort()
  25. return
  26. }
  27. if service.IsBlacklist(token, modelToken) {
  28. response.Result(response.ERROR, gin.H{
  29. "reload": true,
  30. }, "您的帐户异地登陆或令牌失效", c)
  31. c.Abort()
  32. return
  33. }
  34. j := NewJWT()
  35. // parseToken 解析token包含的信息
  36. claims, err := j.ParseToken(token)
  37. if err != nil {
  38. if err == TokenExpired {
  39. response.Result(response.ERROR, gin.H{
  40. "reload": true,
  41. }, "授权已过期", c)
  42. c.Abort()
  43. return
  44. }
  45. response.Result(response.ERROR, gin.H{
  46. "reload": true,
  47. }, err.Error(), c)
  48. c.Abort()
  49. return
  50. }
  51. c.Set("claims", claims)
  52. c.Next()
  53. }
  54. }
  55. type JWT struct {
  56. SigningKey []byte
  57. }
  58. var (
  59. TokenExpired error = errors.New("Token is expired")
  60. TokenNotValidYet error = errors.New("Token not active yet")
  61. TokenMalformed error = errors.New("That's not even a token")
  62. TokenInvalid error = errors.New("Couldn't handle this token:")
  63. )
  64. func NewJWT() *JWT {
  65. return &JWT{
  66. []byte(global.GVA_CONFIG.JWT.SigningKey),
  67. }
  68. }
  69. //创建一个token
  70. func (j *JWT) CreateToken(claims request.CustomClaims) (string, error) {
  71. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  72. return token.SignedString(j.SigningKey)
  73. }
  74. //解析 token
  75. func (j *JWT) ParseToken(tokenString string) (*request.CustomClaims, error) {
  76. token, err := jwt.ParseWithClaims(tokenString, &request.CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {
  77. return j.SigningKey, nil
  78. })
  79. if err != nil {
  80. if ve, ok := err.(*jwt.ValidationError); ok {
  81. if ve.Errors&jwt.ValidationErrorMalformed != 0 {
  82. return nil, TokenMalformed
  83. } else if ve.Errors&jwt.ValidationErrorExpired != 0 {
  84. // Token is expired
  85. return nil, TokenExpired
  86. } else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
  87. return nil, TokenNotValidYet
  88. } else {
  89. return nil, TokenInvalid
  90. }
  91. }
  92. }
  93. if token != nil {
  94. if claims, ok := token.Claims.(*request.CustomClaims); ok && token.Valid {
  95. return claims, nil
  96. }
  97. return nil, TokenInvalid
  98. } else {
  99. return nil, TokenInvalid
  100. }
  101. }
  102. // 更新token
  103. func (j *JWT) RefreshToken(tokenString string) (string, error) {
  104. jwt.TimeFunc = func() time.Time {
  105. return time.Unix(0, 0)
  106. }
  107. token, err := jwt.ParseWithClaims(tokenString, &request.CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
  108. return j.SigningKey, nil
  109. })
  110. if err != nil {
  111. return "", err
  112. }
  113. if claims, ok := token.Claims.(*request.CustomClaims); ok && token.Valid {
  114. jwt.TimeFunc = time.Now
  115. claims.StandardClaims.ExpiresAt = time.Now().Add(1 * time.Hour).Unix()
  116. return j.CreateToken(*claims)
  117. }
  118. return "", TokenInvalid
  119. }