求教用过jwt-go类库使用问题

forrestsun · · 813 次点击 · 开始浏览   
``` go package main import ( "fmt" "github.com/dgrijalva/jwt-go" "time" ) var mySingningKey = []byte("secret") func createToken() (string, error) { claims := jwt.MapClaims{ "uid": "111111", "exp": time.Now().Add(time.Second * 4).Unix(), "iss": "auth.sunsl.net", } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) getTokenRemainingValidity(claims["exp"]) tokenstring, err := token.SignedString(mySingningKey) if err != nil { return "", err } return tokenstring, nil } func RequireTokenAuthentication(tokenstring string) (bool, int) { token, _ := jwt.ParseWithClaims(tokenstring, jwt.MapClaims{}, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("error") } return mySingningKey, nil }) return token.Valid, getTokenRemainingValidity(token.Claims.(jwt.MapClaims)["exp"]) } func getTokenRemainingValidity(timestamp interface{}) int { if validity, ok := timestamp.(float64); ok { tm := time.Unix(int64(validity), 0) remainer := tm.Sub(time.Now()) if remainer > 0 { fmt.Println("*") return int(remainer.Seconds()) } } return -1 } func main() { tokenstring, _ := createToken() valid, rtime := RequireTokenAuthentication(tokenstring) fmt.Printf("1:%v:%v\n", valid, rtime) time.Sleep(time.Second * 2) valid, rtime = RequireTokenAuthentication(tokenstring) fmt.Printf("2:%v:%v\n", valid, rtime) time.Sleep(time.Second * 2) valid, rtime = RequireTokenAuthentication(tokenstring) fmt.Printf("3:%v:%v\n", valid, rtime) time.Sleep(time.Second * 2) valid, rtime = RequireTokenAuthentication(tokenstring) fmt.Printf("4:%v:%v\n", valid, rtime) time.Sleep(time.Second * 2) valid, rtime = RequireTokenAuthentication(tokenstring) fmt.Printf("5:%v:%v\n", valid, rtime) } ``` 结果如下: ``` [ `go run main.go` | done: 8.580037361s ] 1:true:3 2:true:1 3:true:-1 4:false:-1 5:false:-1 ``` 设定周期为4秒,每隔两秒获取一次检验,为什么第三次明明时效已过却还是返回true?
813 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet