jwt.go 873 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package jwt
  2. import (
  3. "errors"
  4. "github.com/dgrijalva/jwt-go"
  5. "time"
  6. )
  7. type Playload struct {
  8. UserId string
  9. Phone string
  10. Expire int64
  11. Role int //角色信息
  12. }
  13. func (p *Playload) Valid() error {
  14. //目前这里想到的是验证超时
  15. if p.Expire < time.Now().Unix() {
  16. return errors.New("timeout")
  17. }
  18. return nil
  19. }
  20. func GenerateToken(pl *Playload, secretKey string) (string, error) {
  21. token := jwt.NewWithClaims(jwt.SigningMethodHS256, pl)
  22. return token.SignedString([]byte(secretKey))
  23. }
  24. func ParseToken(tokenStr string, secretKey string) (*Playload, error) {
  25. var pl Playload
  26. token, err := jwt.ParseWithClaims(tokenStr, &pl, func(token *jwt.Token) (interface{}, error) {
  27. return []byte(secretKey), nil
  28. })
  29. if err != nil {
  30. return nil, err
  31. }
  32. if claims, ok := token.Claims.(*Playload); ok {
  33. return claims, nil
  34. }
  35. return nil, errors.New("not type")
  36. }