jwt.go 1.18 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14
package jwt

import (
	"github.com/dgrijalva/jwt-go"
	"time"
)

// 载荷,增加用户别名
type Claims struct {
	UserId     uint64
	ExternalId string
	jwt.StandardClaims
}

hujiebin's avatar
hujiebin committed
15
// 生成token
hujiebin's avatar
hujiebin committed
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
func GenerateToken(userId uint64, externalId string, issuer string) (string, error) {
	duration, err := time.ParseDuration("240h")
	if err != nil {
		return "", err
	}

	expireTime := time.Now().Add(duration)
	claims := Claims{
		UserId:     userId,
		ExternalId: externalId,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(), //过期时间
			Issuer:    issuer,            //签名的发行者
		},
	}
	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	token, err := tokenClaims.SignedString(GetJWTSecret())
	return token, err
}

func GetJWTSecret() []byte {
	return []byte("hilo1632")
}

hujiebin's avatar
hujiebin committed
40
// 解析token
hujiebin's avatar
hujiebin committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
func ParseToken(token string) (*Claims, error) {
	tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return GetJWTSecret(), nil
	})
	if err != nil {
		return nil, err
	}
	if tokenClaims != nil {
		claims, ok := tokenClaims.Claims.(*Claims)
		if ok && tokenClaims.Valid {
			return claims, nil
		}
	}
	return nil, err
}