jwt_tools.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package jwt_tools
  2. import (
  3. "github.com/dgrijalva/jwt-go"
  4. "github.com/pkg/errors"
  5. "time"
  6. )
  7. func NewJWT(secretKey string, userID string, expSec int64) (string, error) {
  8. token := jwt.New(jwt.SigningMethodHS256)
  9. claims := make(jwt.MapClaims)
  10. if expSec > 0 {
  11. claims["exp"] = time.Now().Add(time.Duration(expSec) * time.Second).Unix()
  12. }
  13. claims["aud"] = userID
  14. claims["iat"] = time.Now().Unix()
  15. token.Claims = claims
  16. tokenString, err := token.SignedString([]byte(secretKey))
  17. if err != nil {
  18. return "", errors.New(err.Error())
  19. }
  20. return tokenString, nil
  21. }
  22. func CheckJWT(secretKey string, tokenStr string) (bool, string, error) {
  23. token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
  24. return []byte(secretKey), nil
  25. })
  26. if err != nil {
  27. var validationErr *jwt.ValidationError
  28. ok := errors.As(err, &validationErr)
  29. if !ok {
  30. return false, "", errors.New(err.Error())
  31. }
  32. if validationErr.Errors == jwt.ValidationErrorExpired {
  33. return false, "", nil
  34. }
  35. return false, "", errors.New(err.Error())
  36. }
  37. claims, ok := token.Claims.(jwt.MapClaims)
  38. if !ok {
  39. return false, "", errors.New("类型转换失败")
  40. }
  41. userID, ok := claims["aud"].(string)
  42. if !ok {
  43. return false, "", errors.New("类型转换失败")
  44. }
  45. return token.Valid, userID, nil
  46. }