func main() {
//生成token
maxAge := 60 * 60 * 24
//或者用下面自定义claim
claims := jwt.MapClaims{
"value": &Student{Name: "musong"},
"exp": time.Now().Add(time.Duration(maxAge) * time.Second).Unix(),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString([]byte(SECRETKEY))
if err != nil {
fmt.Println(err)
}
fmt.Printf("token: %v\n", tokenString)
//解析token
ret, err := ParseToken(tokenString)
if err != nil {
fmt.Println(err)
}
s := new(Student)
v := ret["value"]
byt, _ := json.Marshal(v)
err = json.Unmarshal(byt, s)
if err != nil {
// return
}
fmt.Printf("userinfo: %v\n", s)
}
// 解析token
func ParseToken(tokenString string) (jwt.MapClaims, error) {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
return []byte(SECRETKEY), nil
})
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
return claims, nil
} else {
return nil, err
}
}