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

import (
	"errors"
5 6 7
	"strconv"
	"time"

S
songzhibin97 已提交
8 9 10 11 12 13
	"github.com/flipped-aurora/gin-vue-admin/global"
	"github.com/flipped-aurora/gin-vue-admin/model/common/response"
	"github.com/flipped-aurora/gin-vue-admin/model/system"
	"github.com/flipped-aurora/gin-vue-admin/model/system/request"
	"github.com/flipped-aurora/gin-vue-admin/service"

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

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

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

type JWT struct {
	SigningKey []byte
}

var (
80 81 82 83
	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.奇淼( 已提交
84 85 86 87
)

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

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

98 99 100 101 102 103 104 105
// 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
}

106
// 解析 token
107 108
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.奇淼( 已提交
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
		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 {
126
		if claims, ok := token.Claims.(*request.CustomClaims); ok && token.Valid {
Mr.奇淼('s avatar
Mr.奇淼( 已提交
127 128 129 130 131 132 133 134 135 136 137 138
			return claims, nil
		}
		return nil, TokenInvalid

	} else {
		return nil, TokenInvalid

	}

}

// 更新token
Mr.奇淼('s avatar
Mr.奇淼( 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
//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
//}