package jwt_tools import ( "github.com/dgrijalva/jwt-go" "github.com/pkg/errors" "time" ) func NewJWT(secretKey string, userID string, expSec int64) (string, error) { token := jwt.New(jwt.SigningMethodHS256) claims := make(jwt.MapClaims) if expSec > 0 { claims["exp"] = time.Now().Add(time.Duration(expSec) * time.Second).Unix() } claims["aud"] = userID claims["iat"] = time.Now().Unix() token.Claims = claims tokenString, err := token.SignedString([]byte(secretKey)) if err != nil { return "", errors.New(err.Error()) } return tokenString, nil } func CheckJWT(secretKey string, tokenStr string) (bool, string, error) { token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) { return []byte(secretKey), nil }) if err != nil { var validationErr *jwt.ValidationError ok := errors.As(err, &validationErr) if !ok { return false, "", errors.New(err.Error()) } if validationErr.Errors == jwt.ValidationErrorExpired { return false, "", nil } return false, "", errors.New(err.Error()) } claims, ok := token.Claims.(jwt.MapClaims) if !ok { return false, "", errors.New("类型转换失败") } userID, ok := claims["aud"].(string) if !ok { return false, "", errors.New("类型转换失败") } return token.Valid, userID, nil }