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

import (
	"errors"
Mr.奇淼('s avatar
Mr.奇淼( 已提交
5 6
	"gin-vue-admin/global"
	"gin-vue-admin/model"
7
	"gin-vue-admin/model/request"
8
	"gin-vue-admin/model/response"
9
	"gin-vue-admin/service"
Mr.奇淼('s avatar
Mr.奇淼( 已提交
10 11
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
12
	"go.uber.org/zap"
Mr.奇淼('s avatar
Mr.奇淼( 已提交
13
	"strconv"
Mr.奇淼('s avatar
Mr.奇淼( 已提交
14 15 16 17 18
	"time"
)

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

type JWT struct {
	SigningKey []byte
}

var (
76 77 78 79
	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.奇淼( 已提交
80 81 82 83
)

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

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

94
// 解析 token
95 96
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.奇淼( 已提交
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
		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 {
114
		if claims, ok := token.Claims.(*request.CustomClaims); ok && token.Valid {
Mr.奇淼('s avatar
Mr.奇淼( 已提交
115 116 117 118 119 120 121 122 123 124 125 126
			return claims, nil
		}
		return nil, TokenInvalid

	} else {
		return nil, TokenInvalid

	}

}

// 更新token
Mr.奇淼('s avatar
Mr.奇淼( 已提交
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
//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
//}