1.生成token并传给客户端:
token :=jwt.NewWithClaims(jwt.SigningMethodHS256,jwt.MapClaims{
"id":c.ID,
"username":c.Username,
"exp":time.Now().Unix() +60*10,
"nbf":time.Now().Unix(),
"iat":time.Now().Unix(),
})
tokenString,err =token.SignedString([]byte(secret))
2.客户端验证:
func Parse(tokenString string,secret string) (*Context,error) {
ctx := &Context{}
token,err :=jwt.Parse(tokenString,secretFunc(secret))
if err !=nil {
return ctx,err
}else if claims,ok :=token.Claims.(jwt.MapClaims);ok &&token.Valid {
ctx.ID =uint64(claims["id"].(float64))
ctx.Username =claims["username"].(string)
return ctx,nil
}else {
return ctx,err
}
}
func secretFunc(secret string)jwt.Keyfunc {
return func(token *jwt.Token) (interface{},error) {
if _,ok :=token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil,jwt.ErrSignatureInvalid
}
return []byte(secret),nil
}
}
secret是服务器用来加密的密钥