1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
| package jwt
import ( "errors" "github.com/gin-gonic/gin" jwtpkg "github.com/golang-jwt/jwt" "go-api-practice/pkg/app" "go-api-practice/pkg/config" "go-api-practice/pkg/logger" "strings" "time" )
var ( ErrTokenExpired error = errors.New("令牌已过期") ErrTokenExpiredMaxRefresh error = errors.New("令牌已过最大刷新时间") ErrTokenMalformed error = errors.New("请求令牌格式有误") ErrTokenInvalid error = errors.New("请求令牌无效") ErrHeaderEmpty error = errors.New("需要认证才能访问!") ErrHeaderMalformed error = errors.New("请求头中 Authorization 格式有误") )
type JWT struct {
SignKey []byte
MaxRefresh time.Duration }
type JWTCustomClaims struct { UserID string `json:"user_id"` UserName string `json:"user_name"` ExpireAtTime int64 `json:"expire_time"`
jwtpkg.StandardClaims }
func NewJWT() *JWT { return &JWT{ SignKey: []byte(config.GetString("app.key")), MaxRefresh: time.Duration(config.GetInt64("jwt.max_refresh_time")) * time.Minute, } }
func (jwt *JWT) ParserToken(c *gin.Context) (*JWTCustomClaims, error) {
tokenString, parseErr := jwt.getTokenFromHeader(c) if parseErr != nil { return nil, parseErr }
token, err := jwt.parseTokenString(tokenString)
if err != nil { validationErr, ok := err.(*jwtpkg.ValidationError) if ok { if validationErr.Errors == jwtpkg.ValidationErrorMalformed { return nil, ErrTokenMalformed } else if validationErr.Errors == jwtpkg.ValidationErrorExpired { return nil, ErrTokenExpired } } return nil, ErrTokenInvalid }
if claims, ok := token.Claims.(*JWTCustomClaims); ok && token.Valid { return claims, nil }
return nil, ErrTokenInvalid }
func (jwt *JWT) RefreshToken(c *gin.Context) (string, error) {
tokenString, parseErr := jwt.getTokenFromHeader(c) if parseErr != nil { return "", parseErr }
token, err := jwt.parseTokenString(tokenString)
if err != nil { validationErr, ok := err.(*jwtpkg.ValidationError) if !ok || validationErr.Errors != jwtpkg.ValidationErrorExpired { return "", err } }
claims := token.Claims.(*JWTCustomClaims)
x := app.TimenowInTimezone().Add(-jwt.MaxRefresh).Unix() if claims.IssuedAt > x { claims.StandardClaims.ExpiresAt = jwt.expireAtTime() return jwt.createToken(*claims) }
return "", ErrTokenExpiredMaxRefresh }
func (jwt *JWT) IssueToken(userID string, userName string) string {
expireAtTime := jwt.expireAtTime() claims := JWTCustomClaims{ userID, userName, expireAtTime, jwtpkg.StandardClaims{ NotBefore: app.TimenowInTimezone().Unix(), IssuedAt: app.TimenowInTimezone().Unix(), ExpiresAt: expireAtTime, Issuer: config.GetString("app.name"), }, }
token, err := jwt.createToken(claims) if err != nil { logger.LogIf(err) return "" }
return token }
func (jwt *JWT) createToken(claims JWTCustomClaims) (string, error) { token := jwtpkg.NewWithClaims(jwtpkg.SigningMethodHS256, claims) return token.SignedString(jwt.SignKey) }
func (jwt *JWT) expireAtTime() int64 { timenow := app.TimenowInTimezone()
var expireTime int64 if config.GetBool("app.debug") { expireTime = config.GetInt64("jwt.debug_expire_time") } else { expireTime = config.GetInt64("jwt.expire_time") }
expire := time.Duration(expireTime) * time.Minute return timenow.Add(expire).Unix() }
func (jwt *JWT) parseTokenString(tokenString string) (*jwtpkg.Token, error) { return jwtpkg.ParseWithClaims(tokenString, &JWTCustomClaims{}, func(token *jwtpkg.Token) (interface{}, error) { return jwt.SignKey, nil }) }
func (jwt *JWT) getTokenFromHeader(c *gin.Context) (string, error) { authHeader := c.Request.Header.Get("Authorization") if authHeader == "" { return "", ErrHeaderEmpty } parts := strings.SplitN(authHeader, " ", 2) if !(len(parts) == 2 && parts[0] == "Bearer") { return "", ErrHeaderMalformed } return parts[1], nil }
|