jwt.go 618 Bytes
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 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
package common

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

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

func SetJWTSecret(secret string) {
	jwtSecret = []byte(secret)
}
var jwtSecret []byte

//解析token
func ParseToken(token string) (*Claims, error) {
	tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return jwtSecret, 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
}