package utils import ( "errors" "github.com/golang-jwt/jwt/v4" "github.com/spf13/viper" ) type JWT struct { SigningKey []byte } var ( TokenExpired = errors.New("token已过期") TokenNotValidYet = errors.New("token未生效") TokenMalformed = errors.New("token非法") TokenInvalid = errors.New("无法处理此token") ) func NewJWT() *JWT { return &JWT{ []byte(viper.GetString("signingKey")), } } // CreateToken 创建一个token func (j *JWT) CreateToken(claims CustomClaims) (string, error) { token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) return token.SignedString(j.SigningKey) } // ParseToken 解析 token func (j *JWT) ParseToken(tokenString string) (*CustomClaims, error) { token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) { 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 { if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid { return claims, nil } return nil, TokenInvalid } else { return nil, TokenInvalid } } type CustomClaims struct { ID uint Name string Uuid string BufferTime int64 jwt.StandardClaims }