12345678910111213141516171819202122232425262728293031323334353637383940 |
- package jwt
- import (
- "errors"
- "github.com/dgrijalva/jwt-go"
- "time"
- )
- type Playload struct {
- UserId string
- Phone string
- Expire int64
- Role int //角色信息
- }
- func (p *Playload) Valid() error {
- //目前这里想到的是验证超时
- if p.Expire < time.Now().Unix() {
- return errors.New("timeout")
- }
- return nil
- }
- func GenerateToken(pl *Playload, secretKey string) (string, error) {
- token := jwt.NewWithClaims(jwt.SigningMethodHS256, pl)
- return token.SignedString([]byte(secretKey))
- }
- func ParseToken(tokenStr string, secretKey string) (*Playload, error) {
- var pl Playload
- token, err := jwt.ParseWithClaims(tokenStr, &pl, func(token *jwt.Token) (interface{}, error) {
- return []byte(secretKey), nil
- })
- if err != nil {
- return nil, err
- }
- if claims, ok := token.Claims.(*Playload); ok {
- return claims, nil
- }
- return nil, errors.New("not type")
- }
|