jwt_tools.go 1.3 KB

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