1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- 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
- }
|