jwt.go 1.3 KB

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