jwt.go 982 字节
package utils

import (
	"time"

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

var (
	key = []byte("sx87sda0w7x7sd")
)

//MyToken ...
type MyToken struct {
	jwt.StandardClaims
	ID int `json:"id"`
}

//CreateJWTToken ...
func CreateJWTToken(id int) (string, error) {
	nowTime := time.Now().Unix()
	claims := MyToken{
		StandardClaims: jwt.StandardClaims{
			NotBefore: nowTime,
			IssuedAt:  nowTime,
			ExpiresAt: 60 * 60 * 2, //过期时间
			Issuer:    "test_a",
		},
		ID: id,
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(key)
}

//ValidJWTToken ...
func ValidJWTToken(tokenString string) (*MyToken, error) {
	token, err := jwt.ParseWithClaims(
		tokenString,
		&MyToken{},
		func(token *jwt.Token) (interface{}, error) {
			return key, nil
		})
	if err != nil {
		return nil, err
	}
	if claims, ok := token.Claims.(*MyToken); ok && token.Valid {
		// 验证成功,返回信息
		return claims, nil
	}
	// 验证失败
	return nil, err
}