jwt.go 1.36 KB
Newer Older
chenweijian's avatar
chenweijian committed
1 2 3
package jwt

import (
hujiebin's avatar
hujiebin committed
4
	"git.hilo.cn/hilo-common/resource/config"
chenweijian's avatar
chenweijian committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
	"github.com/dgrijalva/jwt-go"
	"hilo-user/myerr"
	"time"
)

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

//生成token
func GenerateToken(userId uint64, externalId string, issuer string) (string, error) {
	jwtConfig := config.GetConfigJWT()
	duration, err := time.ParseDuration(jwtConfig.EXPIRE)
	if err != nil {
		return "", myerr.WrapErr(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, myerr.WrapErr(err)
}

func GetJWTSecret() []byte {
	return []byte(config.GetConfigJWT().SECRET)
}

//解析token
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, myerr.WrapErr(err)
	}
	if tokenClaims != nil {
		claims, ok := tokenClaims.Claims.(*Claims)
		if ok && tokenClaims.Valid {
			return claims, nil
		}
	}
	return nil, myerr.WrapErr(err)
}