jwt.go 4.7 KB
Newer Older
Mr.奇淼('s avatar
Mr.奇淼( 已提交
1 2 3 4
package middleware

import (
	"errors"
Mr.奇淼('s avatar
Mr.奇淼( 已提交
5
	"gin-vue-admin/global"
6
	"gin-vue-admin/model/common/response"
Mr.奇淼('s avatar
Mr.奇淼( 已提交
7 8
	"gin-vue-admin/model/system"
	"gin-vue-admin/model/system/request"
9
	"gin-vue-admin/service"
10 11 12
	"strconv"
	"time"

Mr.奇淼('s avatar
Mr.奇淼( 已提交
13 14
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
15
	"go.uber.org/zap"
Mr.奇淼('s avatar
Mr.奇淼( 已提交
16 17
)

18 19
var jwtService = service.ServiceGroupApp.SystemServiceGroup.JwtService

Mr.奇淼('s avatar
Mr.奇淼( 已提交
20 21
func JWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
B
Beck Qin 已提交
22
		// 我们这里jwt鉴权取头部信息 x-token 登录时回返回token信息 这里前端需要把token存储到cookie或者本地localStorage中 不过需要跟后端协商过期时间 可以约定刷新令牌或者重新登录
Mr.奇淼('s avatar
Mr.奇淼( 已提交
23 24
		token := c.Request.Header.Get("x-token")
		if token == "" {
25
			response.FailWithDetailed(gin.H{"reload": true}, "未登录或非法访问", c)
Mr.奇淼('s avatar
Mr.奇淼( 已提交
26 27 28
			c.Abort()
			return
		}
29
		if jwtService.IsBlacklist(token) {
30
			response.FailWithDetailed(gin.H{"reload": true}, "您的帐户异地登陆或令牌失效", c)
31 32 33
			c.Abort()
			return
		}
Mr.奇淼('s avatar
Mr.奇淼( 已提交
34 35 36 37 38
		j := NewJWT()
		// parseToken 解析token包含的信息
		claims, err := j.ParseToken(token)
		if err != nil {
			if err == TokenExpired {
39
				response.FailWithDetailed(gin.H{"reload": true}, "授权已过期", c)
Mr.奇淼('s avatar
Mr.奇淼( 已提交
40 41 42
				c.Abort()
				return
			}
43
			response.FailWithDetailed(gin.H{"reload": true}, err.Error(), c)
Mr.奇淼('s avatar
Mr.奇淼( 已提交
44 45 46
			c.Abort()
			return
		}
47 48
		if err, _ = userService.FindUserByUuid(claims.UUID.String()); err != nil {
			_ = jwtService.JsonInBlacklist(system.JwtBlacklist{Jwt: token})
49
			response.FailWithDetailed(gin.H{"reload": true}, err.Error(), c)
50 51
			c.Abort()
		}
52
		if claims.ExpiresAt-time.Now().Unix() < claims.BufferTime {
53
			claims.ExpiresAt = time.Now().Unix() + global.GVA_CONFIG.JWT.ExpiresTime
54
			newToken, _ := j.CreateTokenByOldToken(token, *claims)
55 56 57
			newClaims, _ := j.ParseToken(newToken)
			c.Header("new-token", newToken)
			c.Header("new-expires-at", strconv.FormatInt(newClaims.ExpiresAt, 10))
Mr.奇淼('s avatar
Mr.奇淼( 已提交
58
			if global.GVA_CONFIG.System.UseMultipoint {
59
				err, RedisJwtToken := jwtService.GetRedisJWT(newClaims.Username)
60 61 62
				if err != nil {
					global.GVA_LOG.Error("get redis jwt failed", zap.Any("err", err))
				} else { // 当之前的取成功时才进行拉黑操作
63
					_ = jwtService.JsonInBlacklist(system.JwtBlacklist{Jwt: RedisJwtToken})
Mr.奇淼('s avatar
Mr.奇淼( 已提交
64 65
				}
				// 无论如何都要记录当前的活跃状态
66
				_ = jwtService.SetRedisJWT(newToken, newClaims.Username)
Mr.奇淼('s avatar
Mr.奇淼( 已提交
67 68
			}
		}
Mr.奇淼('s avatar
Mr.奇淼( 已提交
69
		c.Set("claims", claims)
70
		c.Next()
Mr.奇淼('s avatar
Mr.奇淼( 已提交
71 72 73 74 75 76 77 78
	}
}

type JWT struct {
	SigningKey []byte
}

var (
79 80 81 82
	TokenExpired     = errors.New("Token is expired")
	TokenNotValidYet = errors.New("Token not active yet")
	TokenMalformed   = errors.New("That's not even a token")
	TokenInvalid     = errors.New("Couldn't handle this token:")
Mr.奇淼('s avatar
Mr.奇淼( 已提交
83 84 85 86
)

func NewJWT() *JWT {
	return &JWT{
Mr.奇淼('s avatar
Mr.奇淼( 已提交
87
		[]byte(global.GVA_CONFIG.JWT.SigningKey),
Mr.奇淼('s avatar
Mr.奇淼( 已提交
88 89 90
	}
}

91
// 创建一个token
Mr.奇淼('s avatar
Mr.奇淼( 已提交
92
func (j *JWT) CreateToken(claims request.CustomClaims) (string, error) {
Mr.奇淼('s avatar
Mr.奇淼( 已提交
93 94 95 96
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(j.SigningKey)
}

97 98 99 100 101 102 103 104
// CreateTokenByOldToken 旧token 换新token 使用归并回源避免并发问题
func (j *JWT) CreateTokenByOldToken(oldToken string, claims request.CustomClaims) (string, error) {
	v, err, _ := global.GVA_Concurrency_Control.Do("JWT:"+oldToken, func() (interface{}, error) {
		return j.CreateToken(claims)
	})
	return v.(string), err
}

105
// 解析 token
106 107
func (j *JWT) ParseToken(tokenString string) (*request.CustomClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &request.CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {
Mr.奇淼('s avatar
Mr.奇淼( 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
		return j.SigningKey, nil
	})
	if err != nil {
		if ve, ok := err.(*jwt.ValidationError); ok {
			if ve.Errors&jwt.ValidationErrorMalformed != 0 {
				return nil, TokenMalformed
			} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
				// Token is expired
				return nil, TokenExpired
			} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
				return nil, TokenNotValidYet
			} else {
				return nil, TokenInvalid
			}
		}
	}
	if token != nil {
125
		if claims, ok := token.Claims.(*request.CustomClaims); ok && token.Valid {
Mr.奇淼('s avatar
Mr.奇淼( 已提交
126 127 128 129 130 131 132 133 134 135 136 137
			return claims, nil
		}
		return nil, TokenInvalid

	} else {
		return nil, TokenInvalid

	}

}

// 更新token
Mr.奇淼('s avatar
Mr.奇淼( 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
//func (j *JWT) RefreshToken(tokenString string) (string, error) {
//	jwt.TimeFunc = func() time.Time {
//		return time.Unix(0, 0)
//	}
//	token, err := jwt.ParseWithClaims(tokenString, &request.CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
//		return j.SigningKey, nil
//	})
//	if err != nil {
//		return "", err
//	}
//	if claims, ok := token.Claims.(*request.CustomClaims); ok && token.Valid {
//		jwt.TimeFunc = time.Now
//		claims.StandardClaims.ExpiresAt = time.Now().Unix() + 60*60*24*7
//		return j.CreateToken(*claims)
//	}
//	return "", TokenInvalid
//}